以下控制台窗口代码说明了我试图在同一程序集中对多个相同类实例进行反序列化的问题:
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 { }
为了强调,我需要对重复的类实例进行反序列化。