我需要将 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/