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

不打扰是莪最后的温柔 提交于 2019-11-27 13:50:29

问题


I'm working on becoming as familiar with C# as I am with VB.NET (the language used at my workplace). One of the best things about the learning process is that by learning about the other language you tend to learn more about your primary language--little questions like this pop up:

According to the sources I've found, and past experience, a field in VB.NET that is declared as WithEvents is capable of raising events. I understand that C# doesn't have a direct equivalent--but my question is: fields without this keyword in VB.NET cannot raise events, is there a way to create this same behavior in C#? Does the VB compiler simply block these objects from having their events handled (while actually allowing them to raise events as usual)?

I'm just curious; I don't have any particular application for the question...


回答1:


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


来源:https://stackoverflow.com/questions/840691/vb-net-withevents-keyword-behavior-vb-net-compiler-restriction

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