BinaryFormatter和反序列化复杂对象
问题描述:
无法反序列化以下对象图。 System.Runtime.Serialization.SerializationException:BinaryFormatter和反序列化复杂对象
The constructor to deserialize an object of type 'C' was not found.
这里有两种构造函数C.我认为问题可能是:虽然序列化的BinaryFormatter使用paramatered之一,并在呼吁BinaryFormmater反序列化方法时发生该异常在反序列化过程中,它需要一个无参数的过程。有没有黑客/解决方案? 对象:
[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
答
我怀疑你只需要提供一个反序列化的构造函数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<int,A>
{
private Dictionary<int,A> _inner = new Dictionary<int,A>;
// implement interface ...
}
的问题是字典派生类的序列化。