VB.NET WithEvents keyword behavior - VB.NET compiler restriction?

假如想象 提交于 2019-11-28 21:26:08
Craig Gidney

Omitting WithEvents doesn't block members from raising events. It just stops you from using the 'handles' keyword on their events.

Here is a typical use of WithEvents:

Class C1
    Public WithEvents ev As New EventThrower()
    Public Sub catcher() Handles ev.event
        Debug.print("Event")
    End Sub
End Class

Here is a class which doesn't use WithEvents and is approximately equivalent. It demonstrates why WithEvents is quite useful:

Class C2
    Private _ev As EventThrower
    Public Property ev() As EventThrower

        Get
            Return _ev
        End Get

        Set(ByVal value As EventThrower)
            If _ev IsNot Nothing Then
                    removehandler _ev.event, addressof catcher
            End If
            _ev = value
            If _ev IsNot Nothing Then
                    addhandler _ev.event, addressof catcher
            End If
        End Set
    End Property

    Public Sub New()
        ev = New EventThrower()
    End Sub

    Public Sub catcher()
        Debug.print("Event")
    End Sub
End Class
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!