c# - BinaryFormatter 和 Deserialization Complex 对象

标签 c# binaryformatter

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

最佳答案

我怀疑您只需要为 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# - BinaryFormatter 和 Deserialization Complex 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5017274/

相关文章:

c# - 互换使用 BinaryFormatter 和 XmlSerializer

c# - 有没有办法实现 ZeroMQ 全双工 channel ?

c# - 什么是最好的计算平台 SQL 或 c#

.net - 我可以使用 protobuf-net 在 Mono 中序列化一个对象(包含成员 : Dictionary, 列表...等)并在 MS.NET 中反序列化它,反之亦然?

c# - 检查 Binary Formatter 的序列化是否已完成

c# - 反序列化时字典为空

c# - 从文本文件中删除 <div>?

c# - 如何连接用不同语言编写的客户端服务器

c# - 在构建时将 ASPX 中的字符串替换为构建版本

c# - 反序列化为通用排序列表 C#