.NET 3/4 是否允许对事件进行二进制反/序列化?

发布于 2024-08-22 18:58:56 字数 702 浏览 0 评论 0原文

在 .NET 中(至少 <=2),当事件由不可序列化的对象(如 Windows 窗体)处理时,序列化引发事件的对象会出现问题。

由于 VB.NET 实现事件的方式,当您序列化一个对象时,它的事件也会被序列化(因为事件实际上是使用隐藏的多播委托字段来实现的)。这样做的副作用是,任何处理由被序列化的对象引发的事件的对象都将被视为对象图的一部分,并且也将被序列化。

可以找到一些解决方法,实现自定义序列化或使用委托而不是事件:

然而,它们似乎都不能完全满足作者和用户的要求。

.NET 3 / 4 解决这个问题了吗?

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 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:

However none of them seems to completely satisfy the authors and users.

Does the .NET 3 / 4 solve this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╄→承喏 2024-08-29 18:58:56

事件通过创建委托成员来处理。如果您自己显式定义此成员,则应该能够向其添加 NonSerialized 属性。 请参阅此线程以获取参考.

例如:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文