BinaryFormatter and Deserialization Complex objects

前端 未结 2 1254
醉酒成梦
醉酒成梦 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
         }
     }
    

提交回复
热议问题