序列化XML时出现System.NullReferenceException

时间:2014-04-08 04:43:51

标签: c# xml nullreferenceexception

我想序列化简单类,例如如下所示,并写入XML文件。

示例类文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SampleXMLSerializeDeserialize
{
    public class SampleXML
    {
        public SampleXML()
        {

        }
        public List<IndividualInfo> IndividualInfo { get; set; }
        public List<CommunicationInfo> Communication { get; set; }
    }

    public class IndividualInfo
    {
        public String Name { get; set; }
        public String Age { get; set; }
    }

    public class CommunicationInfo
    {
        public String presentAdd { get; set; }
        public String permanentAdd { get; set; }
    }
}

序列化方法:

namespace SampleXMLSerializeDeserialize
{
    class Program
    {
        static void Main(string[] args)
        {
            SampleXML s = new SampleXML();
            s.IndividualInfo[0].Name="Jyoti";
            s.IndividualInfo[0].Age = "25";

            s.Communication[0].permanentAdd = "Dhaka";
            s.Communication[0].presentAdd = "Dhaka";
            XmlSerializer serializer = new XmlSerializer(typeof(SampleXML));
            StreamWriter str = new StreamWriter(Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + @"\SAM.XML");
            serializer.Serialize(str, s);
        }
    }
}

我在以下行获取System.NullReferenceExeption:s.IndividualInfo [0] .Name =“Jyoti”;

请你帮忙,我缺少什么

2 个答案:

答案 0 :(得分:3)

您永远不会实例化集合的[0]对象和集合本身。使用此:

s.IndividualInfo = new List<IndividualInfo>();
s.IndividualInfo.Add(new IndividualInfo { Name = "Jyoti" });

答案 1 :(得分:0)

将您的构造函数设为

    public SampleXML()
    {
     IndividualInfo = new List<IndividualInfo>();
     Communication = new List<CommunicationInfo>();
    }

列表未初始化且为空。 对其他列表也这样做。

然后使用Add方法而不是索引访问。

s.IndividualInfo.Add(new IndividualInfo { Name = "Jyoti", Age = 25 });