Xml序列化自引用/循环引用问题1

1.定义类

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }

    //[XmlIgnore]
    public Student StudentInfo { get; set; }
}

2.执行序列化操作,如果内部对象引用自己,xml序列化抛出异常“检测到循环引用”

Student stu = new Student();
stu.ID = 1;
stu.Name = "张三";
//如果内部引用自己,Xml就会抛出异常
//序列化类型 Test.Student 的对象时检测到循环引用。
/*
    * 解决方案1:在StudentInfo 添加 [XmlIgnore] ,序列化时忽略当前属性
    */
stu.StudentInfo = stu;
//如果内部引用不是自己,不会抛出异常
stu.StudentInfo = new Student()
{
    ID = 2,
    Name = "李四"
};
XmlSerializer xmls = new XmlSerializer(stu.GetType());
string content;
using (MemoryStream ms = new MemoryStream())
{
    xmls.Serialize(ms, stu);
    ms.Position = 0;
    using (StreamReader reader = new StreamReader(ms))
    {
        content = reader.ReadToEnd();
    }
}
Console.WriteLine(content);

如果内部对象不是引用的自己,则可以使用

原文地址:https://www.cnblogs.com/tianma3798/p/5481559.html