BinaryFormatter和Deserialization Complex对象

无法反序列化以下对象图。 在BinaryFormmater上调用deserialize方法时发生exception:System.Runtime.Serialization.SerializationException:

The constructor to deserialize an object of type 'C' was not found. 

C上有两个构造函数,我认为问题可能是:序列化Binaryformatter使用参数化和反序列化过程,它需要一个无参数的。 有黑客/解决方案吗? 对象:

  [Serializable] public class A { B b; C c; public int ID { get; set; } public A() { } public A(B b) { this.b = b; } public A(C c) { this.c = c; } } [Serializable] public class B { } [Serializable] public class C : Dictionary { public C() { } public C(List list) { list.ForEach(p => this.Add(p.ID, p)); } } 

//序列化成功

  byte[] result; using (var stream =new MemoryStream()) { new BinaryFormatter ().Serialize (stream, source); stream.Flush (); result = stream.ToArray (); } return result; 

//反序列化失败

  object result = null; using (var stream = new MemoryStream(buffer)) { result = new BinaryFormatter ().Deserialize (stream); } return result; 

调用是在相同的环境,相同的线程,相同的方法

  List alist = new List() { new A {ID = 1}, new A {ID = 2} }; C c = new C(alist); var fetched = Serialize (c); // success var obj = Deserialize(fetched); // failes 

我怀疑你只需要为C提供一个反序列化构造函数,因为字典实现了ISerializable

 protected C(SerializationInfo info, StreamingContext ctx) : base(info, ctx) {} 

检查(通过):

  static void Main() { C c = new C(); c.Add(123, new A { ID = 456}); using(var ms = new MemoryStream()) { var ser = new BinaryFormatter(); ser.Serialize(ms, c); ms.Position = 0; C clone = (C)ser.Deserialize(ms); Console.WriteLine(clone.Count); // writes 1 Console.WriteLine(clone[123].ID); // writes 456 } } 

当您按如下方式实现C类时,您的序列化将成功:

 [Serializable] public class C : IDictionary { private Dictionary _inner = new Dictionary; // implement interface ... } 

问题是Dictionary派生类的序列化。