如何序列化/反序列化分布在程序集中的多个相同类实例

时间:2019-06-02 23:09:40

标签: c#

以下控制台窗口代码说明了我试图在同一程序集中对多个相同类实例进行反序列化的问题:

class Program
{
    static void Main(string[] args)
    {
        const string fnam = "MyFile.bin";
        Dummy a = new Dummy();
        Dummy b = a;

        Console.WriteLine($"a == b {a == b}"); // true

        var formatter = new BinaryFormatter();
        Stream stream = new FileStream(fnam, FileMode.Create, FileAccess.Write, FileShare.None);
        formatter.Serialize(stream, a);
        formatter.Serialize(stream, b);
        stream.Close();

        stream = new FileStream(fnam, FileMode.Open, FileAccess.Read, FileShare.Read);
        a = (Dummy)formatter.Deserialize(stream);
        b = (Dummy)formatter.Deserialize(stream);
        stream.Close();

        Console.WriteLine($"a == b {a == b}"); // false

        File.Delete(fnam);
    }
}
[Serializable]
class Dummy { }

为了强调,我需要对重复的类实例进行反序列化。

0 个答案:

没有答案