【问题标题】:C# how to check if an attribute returns null?C#如何检查属性是否返回null?
【发布时间】:2018-03-07 07:58:00
【问题描述】:

我是 C# 新手。我有以下代码:

            XmlNodeList elemList = xmlFile.GetElementsByTagName("Position");

        for (int i = 0; i < elemList.Count; i++)
        {
            string posNumber = elemList[i].Attributes["PosNumber"].Value;
            string posGroup = elemList[i].Attributes["PosGroup"].Value;
            string positionsTypeSK = elemList[i].Attributes["PositionTypeSK"].Value;
            string positionCommercialTypeSK = elemList[i].Attributes["PositionCommercialTypeSK"].Value;
            string positionSK = elemList[i].Attributes["PositionSK"].Value;
            string bookingUnitSK = elemList[i].Attributes["BookingUnitSK"].Value;
            string contentComponentCommSK = elemList[i].Attributes["ContentComponentCommSK"].Value;
            string salesAgentPrice = elemList[i].Attributes["SalesAgentPrice"].Value;

            string bundlePositionSK = (elemList[i].Attributes["BundlePositionSK"] != null).ToString();
            string mainPositionSK = (elemList[i].Attributes["MainPositionSK"] != null).ToString();
            //Now I want the value of the attributes or a empty string here


            listOfNames.Add(new ResultNames(positionSK, posGroup, posNumber, positionCommercialTypeSK, bundlePositionSK, mainPositionSK,
                salesAgentPrice, bookingUnitSK, contentComponentCommSK, positionsTypeSK));
        }
        return listOfNames;

我想检查属性是否返回null。

我试过string bundlePositionSK = (elemList[i].Attributes["BundlePositionSK"] != null).ToString();

但这里它只给我 true 或 false。

如何检查每个属性/值是否为空?如果它为空,它应该给我一个空字符串。

【问题讨论】:

    标签: c#


    【解决方案1】:

    您可以使用null conditional operator:

    string posNumber = elemList[i].Attributes["PosNumber"]?.Value ?? String.Empty;
    

    【讨论】:

    • 没错,但解释一下这个运算符的作用并没有什么坏处。 OP 是 C# 的新手。
    【解决方案2】:

    我认为你的意思是使用string.IsNullOrEmpty:

    string bundlePositionSK = string.IsNullOrEmpty(elemList[i].Attributes["BundlePositionSK"]?.Value)
                              ? string.Empty
                              : elemList[i].Attributes["BundlePositionSK"].Value;
    

    【讨论】:

    • 它说“错误 CS1503 参数 1:无法从 'System.Xml.XmlAttribute' 转换为 'string'”,所以我只添加了一个“.ToString();?
    • Value 是一个字符串,所以它应该可以工作。不知道你是否复制正确。
    【解决方案3】:

    我想你可以先检查它不为空。

    string bundlePositionSK =  elemList[i].Attributes["BundlePositionSK"]!=null
                          ? string.Empty
                          : elemList[i].Attributes["BundlePositionSK"];
    

    【讨论】:

    • 那不会编译。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 2020-04-15
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2010-10-06
    相关资源
    最近更新 更多