如果您搭載在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
。
您究竟如何發送和接收這些對象? – Adam
只是保存/本地加載它們(到文件)XML或二進制 – Sunspear