Not marked as serializable error when serializing a class

前端 未结 2 433
耶瑟儿~
耶瑟儿~ 2021-01-03 22:28

I am serializing an structure by using BinaryFormatter using this code:

private void SerializeObject(string filename, SerializableStructure obje         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-03 23:04

    This almost alwas means you have an event (or other delegate - maybe a callback) somewhere in your object model, that is trying to be serialized. Add [NonSerialized] to any event-backing fields. If you are using a field-like event (the most likely kind), this is:

    [field:NonSerialized]
    public event SomeDelegateType SomeEventName;
    

    Alternatively: most other serializers don't look at events/delegates, and provide better version-compatibility. Switching to XmlSerializer, JavaScriptSerializer, DataContractSerializer or protobuf-net (just 4 examples) would also solve this by the simple approach of not trying to do this (you almost never intend for events to be considered as part of a DTO).

提交回复
热议问题