开发者

Do .NET 3/4 Permits Events to be Binary De/Serialized?

开发者 https://www.devze.com 2022-12-21 10:57 出处:网络
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).

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
0

精彩评论

暂无评论...
验证码 换一张
取 消