序列化時,我想只序列化一個對象一次,然後對該對象的任何引用都應序列化爲對該對象的引用。這是因爲,當我後來反序列化對象時,我想維護這些引用。爲了說明我的目標,下面的代碼應該輸出「序列化後:真」。通過序列化/反序列化維護對象引用
class Program
{
static void Main(string[] args)
{
MyObject obj = new MyObject() { Name = "obj" };
MyObject[] myObjs = new MyObject[]
{
obj, obj
};
Console.WriteLine("Object Refs Equal?");
Console.WriteLine(string.Format("Before Serialization: {0}",
object.ReferenceEquals(myObjs[0], myObjs[1])));
XmlSerializer toXml = new XmlSerializer(typeof(MyObject[]));
using (FileStream toFile = File.Create(@"C:\foo.xml"))
{
toXml.Serialize(toFile, myObjs);
}
XmlSerializer fromXml = new XmlSerializer(typeof(MyObject[]));
using (FileStream fromFile = File.OpenRead(@"C:\foo.xml"))
{
MyObject[] deserialized = (MyObject[])fromXml.Deserialize(fromFile);
Console.WriteLine(string.Format("After Serialization: {0}",
object.ReferenceEquals(deserialized[0], deserialized[1])));
}
Console.ReadLine();
}
}
[Serializable]
public class MyObject
{
public string Name { get; set; }
}
我只是試圖做到這一點,但它不工作,因爲它是隻讀屬性。我在這裏錯過了什麼? – 2012-02-08 01:41:02