jac*_*kie 23 c# binaryformatter
无法反序列化以下对象图.在BinaryFormmater上调用deserialize方法时发生异常:System.Runtime.Serialization.SerializationException:
The constructor to deserialize an object of type 'C' was not found.
Run Code Online (Sandbox Code Playgroud)
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));
}
}
Run Code Online (Sandbox Code Playgroud)
//序列化成功
byte[] result;
using (var stream =new MemoryStream())
{
new BinaryFormatter ().Serialize (stream, source);
stream.Flush ();
result = stream.ToArray ();
}
return result;
Run Code Online (Sandbox Code Playgroud)
//反序列化失败
object result = null;
using (var stream = new MemoryStream(buffer))
{
result = new BinaryFormatter ().Deserialize (stream);
}
return result;
Run Code Online (Sandbox Code Playgroud)
调用是在相同的环境,相同的线程,相同的方法
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
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 37
我怀疑你只需要提供一个反序列化构造函数C,因为字典实现ISerializable:
protected C(SerializationInfo info, StreamingContext ctx) : base(info, ctx) {}
Run Code Online (Sandbox Code Playgroud)
检查(通过):
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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33542 次 |
| 最近记录: |