BinaryFormatter and Deserialization Complex objects

前端 未结 2 1244
醉酒成梦
醉酒成梦 2020-12-03 10:20

Can not deserialize following object graph. That Exception occurs when deserialize method called on BinaryFormmater: System.Runtime.Serialization.SerializationException :

相关标签:
2条回答
  • 2020-12-03 10:41

    I suspect you just need to provide a deserialization constructor to C, since dictionary implements ISerializable:

    protected C(SerializationInfo info, StreamingContext ctx) : base(info, ctx) {}
    

    checked (passes):

     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
         }
     }
    
    0 讨论(0)
  • 2020-12-03 10:59

    Your serialization will succeed when you implement class C as following:

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

    The problem is the serialization of the Dictionary derived class.

    0 讨论(0)
提交回复
热议问题