对象引用未设置为与非现有Datamember相关的Object实例

时间:2016-04-15 22:22:11

标签: c# xml

以下代码是简化版本,由于许多情况,很难创建与原始源代码相同的源代码。

我收到的错误消息是"对象引用未设置为Object的实例"当我输入这段代码" var dd = playerList.FirstName.ToUpper();"因为我的原始源代码中没有datamember FirstName。

我从xml文件中获取具有元素名字的随机数据。如果我没有元素名字,则原始源代码中的数据库将不可用,

我的问题是,

我应该如何使用C#代码知道我是否有数据名FirstName?

谢谢!

<PlayerList>
  <Player>
    <Id>1</Id>
    <FirstName>John</FirstName>
    <LastName>Smith</LastName>
    <TotalGoalsScored>50</TotalGoalsScored>
    <AverageGoalsPerGame>0.7</AverageGoalsPerGame>
    <Team>
      <Name>Arsenal</Name>
      <YearEstablished>0</YearEstablished>
    </Team>
  </Player>
  <Player>
    <Id>2</Id>
    <FirstName>Jack</FirstName>
    <TotalGoalsScored>0</TotalGoalsScored>
    <AverageGoalsPerGame>0</AverageGoalsPerGame>
  </Player>
</PlayerList>




            string inputXmlPath1 = @"C:\dddd\data.xml";
            using (StreamReader reader = new StreamReader(inputXmlPath1))
            {
                XmlSerializer playerListSerializer = new XmlSerializer(typeof(PlayerList));

                var playerList = (PlayerList)playerListSerializer.Deserialize(reader);

                var dd = playerList.FirstName.ToUpper();
            }





    [XmlRoot]
    public class PlayerList
    {
        [XmlElement("Player")]
        public List<Player> Players { get; set; }
    }




    public class Player
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int TotalGoalsScored { get; set; }
        public double AverageGoalsPerGame { get; set; }
    }

1 个答案:

答案 0 :(得分:0)

当您收到此异常时,表示您尝试调用方法(或访问属性)的成员为null

因此,您可以在继续之前将null合并为默认值:

var dd = (playerList.FirstName ?? "").ToUpper(); // dd will be the empty string if FirstName was null

对于C#6,您还可以使用空条件运算符:

var dd = playerList.FirstName?.ToUpper(); // note: dd will be null is FirstName was null

或者使用正常的条件陈述进行检查:

if (playerList.firstName == null) { // handle the null case