[英]Serialize C# Objects while maintaining object references
因此,我有多个自定义类,它们在其实例中引用其他类。 我知道序列化通常如何工作,但是如何处理对象引用? 目标是将对象保存为xml或二进制文件,以便以后可以恢复状态。
在此简化示例中,人物通过ID进行标识,并具有其他称为“朋友”的人物对象列表。
public class Person{
public int id;
public List<Person> friends;
}
我如何序列化和反序列化此示例,并保持对象引用完整无缺? 另外,我认为反序列化如果试图恢复对尚未反序列化的Person的引用,则可能会很棘手。
[XmlRootAttribute("Person")]
public class Person{
[XmlAttribute("_id")]
public int id;
[XmlElement("friends")]
public List<Person> friends;
}
然后使用XmlSerializer类创建xml文件和/或对象https://msdn.microsoft.com/zh-cn/library/58a18dwa.aspx
如果您搭载WCF并使用DataContract
属性并设置IsReference = true
,则可以跟踪引用,然后需要使用DataContractSerializer
来序列化数据。
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
namespace SandboxConsole
{
internal class Program
{
public static void Main()
{
var bob = new Person {Id = 0};
var scott = new Person {Id = 1};
var dave = new Person {Id = 2};
bob.Friends.Add(scott);
bob.Friends.Add(dave);
scott.Friends.Add(dave);
var people = new List<Person>();
people.Add(bob);
people.Add(scott);
people.Add(dave);
using (var fs = File.Create("Test.xml"))
{
var ser = new DataContractSerializer(typeof(List<Person>));
ser.WriteObject(fs, people);
}
List<Person> people2;
using (var fs = File.OpenRead("Test.xml"))
{
var ser = new DataContractSerializer(typeof(List<Person>));
people2 = (List<Person>)ser.ReadObject(fs);
}
Console.WriteLine("Are these daves the same dave?");
Console.WriteLine("List dave, bob's friend - {0}", ReferenceEquals(people2[2], people2[0].Friends[1]));
Console.WriteLine("Bob's firend, scott's friend - {0}", ReferenceEquals(people2[0].Friends[1], people2[1].Friends[0]));
Console.ReadLine();
}
}
[DataContract(IsReference = true)]
public class Person
{
public Person()
{
Friends = new List<Person>();
}
[DataMember]
public int Id { get; set; }
[DataMember]
public List<Person> Friends { get; private set; }
}
}
尝试使用IsRefrence = false
或不带参数(默认为false)运行上述测试程序,对于相同对象的测试,它将输出false
。 但是,如果将其设置为IsRefrence = false
,则对于相同对象的测试将输出true
。
编辑:一个重要的注意事项,我没有办法使RefrenceEquals(people[0], people2[0])
输出true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.