Why is the "NonSerialized" attribute not used at the class level? How to prevent class serialization?

I have a data object that is deeply cloned using binary serialization. This data object supports events with modified properties, such as PriceChanged.

Let's say I attached a handler to PriceChanged. When the code tries to serialize PriceChanged, it throws an exception that the handler is not marked as serializable.

My alternatives:

  • I cannot easily remove all handlers from an event before serializing
  • I do not want to mark the handler as serializable, because I will have to recursively mark all the dependencies of the handlers.
  • I do not want to mark PriceChanged as NonSerialized - there are a dozen similar events that handlers could potentially have. EDIT: Another reason I can't do this is because data classes (and therefore events) are generated, and I don't have direct control over the generation code. Ideally, the generation code would simply mark all events as NonSerialized.
  • Ideally, I would like .NET to just stop going down the graph of objects at that moment and make it a "sheet". So why does .NET not allow you to mark the entire class as NonSerialized?

-

, , , ISerializable serialize constructor/GetDataObject. , , null, .

? , ?

+3
2

( NonSerialized, , ), , , , .

, , ISerializationSurrogate , , - GetObjectData SetObjectData. , , , .

- :

class DelegateSerializationSurrogate : ISerializationSurrogate {
    public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) {
        // do nothing
    }
    public object SetObjectData(object obj, SerializationInfo info, StreamingContext context) {
        // do nothing
        return null;
    }
}

, MSDN. , , .

+4

... ...

, :

[field: NonSerialized]
public event SomeEventType SomeEventName;

( )

? BinaryFormatter ; , (IMO , ).

; , " ":

  • XmlSerializer ( )
  • DataContractSerializer/NetDataContractSerializer
  • protobuf-net ( Serializer.DeepClone )

( , , [NonSerialized]!)

+2

Source: https://habr.com/ru/post/1737459/


All Articles