C# Temporarily unassign event handler for serialisation?
I have an object graph which contains one object which fires events.
I want to serialise this graph, however I occasionally plug handlers into the event which belong to non-serialisable classes, nor do I want those non-serialisable objects to be serialised in the first place.
Basically, non-serialisable things like calendars, reports, graphs, etc. plug into the data graph and the events are for things like updates, etc. I want to serialise my da开发者_开发问答ta graph, but not my reports, calendars, etc.
When I try to serialise my data graph, I get an exception if the event delegate is not null, as the handling classes are non-serialisable. I have code in those Forms such that when I close them, the handlers disconnect, so I can save my data graph as long as I've closed all calendars, reports, etc.
The logical solution would seem to be:
- Set a temporary variable equal to the current state of the event handlers, be it null or otherwise.
- Set the event handlers to null.
- Serialise my data graph.
- Set the event handlers back to what they were before.
However this doesn't work because I'm getting a compile-time error telling my my event can only exist on the left side of += or -=
How can I remove all handlers temporarily while I serialise, and then set them back afterwards?
You could try applying [field:NonSerialized]
to your event?
精彩评论