Not marked as serializable error when serializing a class

前端 未结 2 411
耶瑟儿~
耶瑟儿~ 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).

    0 讨论(0)
  • 2021-01-03 23:04

    The problem is that you are trying to serialize a class derived from Form. The Form class is fundamentally unserializable. It has an enormous amount of internal state that is highly runtime dependent. That starts with an obvious property like Handle, a value that's always different. Less obvious are properties like Size, dependent on user preferences like the size of the font for the window caption. Ends with all the text, location and sizes for the controls, they are subject to localization. The odds that a serialized Form object can be properly deserialized anywhere at any time to create an exact clone of the form are zero.

    Microsoft made no bones about it when they wrote the code, they simply omitted the [Serializable] attribute from the class declaration. Which is why you get the exception.

    You'll have to aim lower, write your own class to capture your form's state. And give it the attribute. You'll need to write a bunch of code that maps between the form and control properties to an object of that class, back and forth.

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