zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    Delphi程序结构
    SQL存储过程解密 Encrypted object is not transferable, and script can not be generated

    在河南呢
    还在河南,写随笔吧
    HAVING
    mIRC
    关于CAP理论
    开篇
    移动信息系统
  • 原文地址:https://www.cnblogs.com/tianma3798/p/5481593.html
Copyright © 2011-2022 走看看