Xml序列化自引用/循环引用问题2
1.类定义:
public class Student { public int ID { get; set; } public string Name { get; set; } //[XmlIgnore] public Grade Grade { get; set; } } public class Grade { public int GradeID { get; set; } public string GradeName { get; set; } public List<Student> Students { get; set; } }
2.如果子类的父类对象,不引用当前的父类对象不会抛出异常
//创建班级 Grade gradeOne = new Grade() { GradeID = 1, GradeName = "班级1" }; gradeOne.Students = new List<Student>(); //添加班级下的学生 Student stu = new Student(); stu.ID = 1; stu.Name = "张三"; //设置学生所属的班级 /* * 1.如果指定学生的班级 就会抛出异常:序列化类型 Test.Grade 的对象时检测到循环引用。 * 2.解决方法1:在创建的时候不指定子类对应的父类 * 3.解决方法2:在子类的父类对象属性,添加[XmlIgnore] */ stu.Grade = gradeOne; gradeOne.Students.Add(stu); XmlSerializer xmls = new XmlSerializer(gradeOne.GetType()); string content; using (MemoryStream ms = new MemoryStream()) { xmls.Serialize(ms, gradeOne); ms.Position = 0; using (StreamReader reader = new StreamReader(ms)) { content = reader.ReadToEnd(); } } Console.WriteLine(content);