In .NET (at least <=2) there's a problem serializing objects that raise events when those events are handled by a non-serializable object (like a Windows Form).
Because of the way VB.NET implements events, when you serialize an object, its events get serialized too (because events are actually implemented using hidden multicast delegate fields). A side effect of this is that any object which handles events raised by the object 开发者_StackOverflow中文版being serialized will be considered part of the object graph and will be serialized too.
Some workarounds could be found, implementing custom serialization or using delegates instead of events:
- http://www.codeproject.com/KB/vb/serializevbclasses.aspx
- http://www.lhotka.net/WeBlog/CommentView.aspx?guid=776f44e8-aaec-4845-b649-e0d840e6de2c
However none of them seems to completely satisfy the authors and users.
Does the .NET 3 / 4 solve this problem?
Events are handled by creation of a delegate member. If you explicitly define this member yourself, you should be able to add the NonSerialized
attribute to it. See this thread for a reference.
For example:
Public Delegate Sub MyEventDelegate()
<NonSerialized()>Private m_MyEventDelegate As MyEventDelegate
Public Custom Event MyEvent As MyEventDelegate
AddHandler(ByVal value As MyEventDelegate)
m_MyEventDelegate = DirectCast(System.Delegate.Combine(m_MyEventDelegate, value), MyEventDelegate)
End AddHandler
RemoveHandler(ByVal value As MyEventDelegate)
m_MyEventDelegate = DirectCast(System.Delegate.Remove(m_MyEventDelegate, value), MyEventDelegate)
End RemoveHandler
RaiseEvent()
If m_MyEventDelegate IsNot Nothing Then
m_MyEventDelegate.Invoke()
End If
End RaiseEvent
End Event
精彩评论