C#如何检查属性是否返回null?

时间:2018-03-07 07:58:01

标签: c#

我是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

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

3 个答案:

答案 0 :(得分:2)

您可以使用null conditional operator

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

答案 1 :(得分:1)

我认为您打算使用string.IsNullOrEmpty

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

答案 2 :(得分:0)

我认为你可以先检查它是否为空。

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