Maintaining object references through Serialize / Deserialize

When serializing, I would like to serialize the object only once, then any references to this object should be serialized as a reference to the object. This is because when I later deserialize the objects, I would like to keep these links. To illustrate my purpose, the code below should output "After serialization: true."

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; }
}
+3
source share
4 answers

If you are using .NET 3 or later, you must use DataContractSerializerand install PreserveObjectReferencesin true.

+2
source

You will need to do this by specifying object identifiers other than an object reference.

- , , . , - .

0

, , ... , .

, :  a) - .  b) .

- , . , a) , b) , .

http://en.csharp-online.net/Glossary:Definition_-_Reference_type

0

, XmlSerializer , , , obj , , . DataContractSerializer, , , , xml (.: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx)

0

Source: https://habr.com/ru/post/1702137/


All Articles