如何序列化&反序列化静态引用对象?

时间:2015-09-03 12:07:49

标签: c# serialization binaryformatter

我想序列化&使用BinaryFormatter反序列化对象(此对象具有引用)。

我曾预料到' DeserializedObject.Equals(A.Empty)'与下面的代码相同。 但是,结果是不同的。

为了反序列化对象== A.Empty',如何使用序列化/反序列化?

[Serializable]
public class A
{
    private string ID = null;
    private string Name = null;

    public A()
    { }

    public static A Empty = new A()
    {
        ID = "Empty",
        Name = "Empty"
    };
}

class Program
{
    static void Main(string[] args)
    {
        A refObject = A.Empty; // Add reference with static object(Empty)
        A DeserializedObject;

        //Test
        //before serialization, refObject and A.Empty is Same!!
        if(refObject.Equals(A.Empty))
        {
            Console.WriteLine("refObject and A.Empty is the same ");
        }

        //serialization
        using (Stream stream = File.Create("C:\\Users\\admin\\Desktop\\test.mbf"))
        {
            BinaryFormatter bin = new BinaryFormatter();
            bin.Serialize(stream, refObject);
        }
        //Deserialization
        using (Stream stream = File.Open("C:\\Users\\admin\\Desktop\\test.mbf", FileMode.Open))
        {
            BinaryFormatter bin = new BinaryFormatter();
            DeserializedObject = (A)bin.Deserialize(stream);
        }

        //compare DeserializedObject and A.Empty again.
        //After deserialization, DeserializedObject and A.Empty is Different!!
        if (DeserializedObject.Equals(A.Empty))
        {
            Console.WriteLine("Same");
        }
        else
            Console.WriteLine("Different");
    }
}

1 个答案:

答案 0 :(得分:1)

原因是他们 不同的对象!您可以通过打印他们的GetHashCode()来检查这一点。原因在于你的代码:

  1. refObject是对A.Empty的引用(因此是同一个对象)
  2. DeserialisedObject不是副本;这是一个新的实例,所以a     不同的对象
  3. 但DeserializedObject应包含相同的值(ID和Name)。请注意,refObject.ID将与A.Empty.ID是同一个对象; DeserialisedObject.ID不会,虽然应该包含相同数据的副本。

    如果您只是测试反序列化是否有效,请测试DeserializedObject和A.Empty包含的值是否相同。