BinaryFormatter和Deserialization Complex对象

时间:2011-02-16 13:51:24

标签: c# binaryformatter

无法反序列化以下对象图。在BinaryFormmater上调用deserialize方法时发生异常: 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

2 个答案:

答案 0 :(得分:37)

我怀疑你只需要为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
     }
 }

答案 1 :(得分:1)

如下所示实现C类时,序列化将成功:

[Serializable]
public class C : IDictionary<int,A>
{
    private Dictionary<int,A> _inner = new Dictionary<int,A>;

    // implement interface ...
}

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