无法反序列化以下对象图。当在 BinaryFormmater 上调用反序列化方法时会发生该异常: 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<int, A>
{
public C()
{
}
public C(List<A> 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<A> alist = new List<A>()
{
new A {ID = 1},
new A {ID = 2}
};
C c = new C(alist);
var fetched = Serialize (c); // success
var obj = Deserialize(fetched); // failes