VB.NET WithEvents关键字行为 - VB.NET编译器限制?

STW*_*STW 15 .net c# vb.net clr vb.net-to-c#

我正在努力熟悉C#,就像我使用VB.NET(我工作场所使用的语言)一样.关于学习过程的最好的事情之一是,通过了解另一种语言,你倾向于更多地了解你的主要语言 - 像这样的小问题弹出:

根据我发现的消息来源和过去的经验,VB.NET中声明为WithEvents的字段能够引发事件.据我所知,C#不具有直接等效-但我的问题是:场没有这个关键字在VB.NET不能引发事件,有没有一种方法来创建在C#中此相同的行为呢?VB编译器是否只是阻止这些对象处理事件(实际上允许它们像往常一样引发事件)?

我只是好奇; 我对这个问题没有任何特别的申请......

Cra*_*ney 21

省略WithEvents不会阻止成员举起活动.它只是阻止你在事件中使用'handles'关键字.

以下是WithEvents的典型用法:

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

这是一个不使用WithEvents的类,大致相当于.它演示了为什么WithEvents非常有用:

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
Run Code Online (Sandbox Code Playgroud)