c# - C# 中的递归序列化

标签 c# recursion xml-serialization

我需要将 myFamily 序列化为一个 .xml 文件,我真的不知道该怎么做。

枚举.cs

public enum Genre {
    Male,
    Female
}

PERSON.cs

public class PERSON {
    public string Name { get; set; }
    public Genre Genre { get; set; }
    public List<PERSON> Parents { get; set; }
    public List<PERSON> Children { get; set; }

    public PERSON(string name, Genre genre) {
        this.Name = name;
        this.Genre = genre;
    }
}

Form1.cs

    private void Form1_Load(object sender, EventArgs e) {
        List<PERSON> myFamily = new List<PERSON>();

        PERSON Andrew = new PERSON("Andrew", Genre.Male);
        PERSON Angela = new PERSON("Angela", Genre.Female);
        PERSON Tina = new PERSON("Tina", Genre.Female);
        PERSON Jason = new PERSON("Jason", Genre.Male);
        PERSON Amanda = new PERSON("Amanda", Genre.Female);
        PERSON Steven = new PERSON("Steven", Genre.Male);

        Andrew.Parents.Add(Tina);
        Andrew.Parents.Add(Jason);

        Angela.Parents.Add(Tina);
        Angela.Parents.Add(Jason);

        Tina.Parents.Add(Amanda);
        Tina.Parents.Add(Steven);

        Jason.Children.Add(Andrew);
        Jason.Children.Add(Angela);

        Tina.Children.Add(Andrew);
        Tina.Children.Add(Angela);

        Amanda.Children.Add(Tina);

        Steven.Children.Add(Tina);

        myFamily.Add(Andrew);
        myFamily.Add(Angela);
        myFamily.Add(Tina);
        myFamily.Add(Jason);
        myFamily.Add(Amanda);
        myFamily.Add(Steven);

        // serialize to an .xml file
    }

最佳答案

要使用循环引用序列化对象,您需要使用 DataContractSerializer .为此

  • 添加[DataContract(IsReference=true)]Person
  • [DataMember] 添加到您的属性中
  • 在构造函数中实例化列表
  • 记得使用System.Runtime.Serialization;

所以你的类应该是:

[DataContract(IsReference=true)]
public class PERSON
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public Genre Genre { get; set; }
    [DataMember]
    public List<PERSON> Parents { get; set; }
    [DataMember]
    public List<PERSON> Children { get; set; }

    public PERSON(string name, Genre genre)
    {
        this.Name = name;
        this.Genre = genre;
        Parents = new List<PERSON>();
        Children = new List<PERSON>();
    }
}

序列化:

var serializer = new DataContractSerializer(myFamily.GetType()); 
using (FileStream stream = File.Create(@"D:\Test.Xml")) 
{ 
    serializer.WriteObject(stream, myFamily); 
} 

反序列化:

using (FileStream stream = File.OpenRead(@"D:\Test.Xml"))
{ 
    List<PERSON> data = (List<PERSON>)serializer.ReadObject(stream); 
}

关于c# - C# 中的递归序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32427593/

相关文章:

c# - 如何将数据源绑定(bind)到标签控件

c# - 使用 MEF 时,为我的插件使用 app.config 的正确方法是什么?

python - 合并三个排序列表的递归 Python 程序

sql - 查询使用子表查找根表到任何级别,递归 CTE?

C#反序列化问题

java - Java 中是否有使用 writeObject 方法的开源对象到 XML 序列化程序

c# - 在数据库中存储第三方服务登录名/密码

java - 递归谢尔宾斯基三角形

c# - C#中通过XmlSerializer类反序列化多个同名XML元素

c# - 如何防止 WebBrowser 控件捕获异常并将它们显示为脚本错误?