序列化XML时出现System.NullReferenceException

本文关键字:System NullReferenceException XML 序列化 | 更新日期: 2023-09-27 17:57:30

我想像下面这样序列化简单的类,并写入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";

你能帮忙吗,我缺少什么

序列化XML时出现System.NullReferenceException

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

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

将构造函数设置为

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

该列表未初始化,并且为null。对其他列表也执行同样的操作。

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

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