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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/840691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:42:10  来源:igfitidea点击:

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

c#.netvb.netclrvb.net-to-c#

提问by STW

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:

我正在努力像熟悉 VB.NET(我工作场所使用的语言)一样熟悉 C#。学习过程中最好的事情之一是,通过学习其他语言,您往往会更多地了解您的主要语言——像这样的小问题会弹出:

According to the sources I've found, and past experience, a field in VB.NET that is declared as WithEventsis capable of raising events. I understand that C# doesn't have a direct equivalent--but my question is: fields withoutthis 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)?

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

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

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

采纳答案by Craig Gidney

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

省略 WithEvents 不会阻止成员引发事件。它只是阻止您在他们的事件中使用 'handles' 关键字。

Here is a typical use of WithEvents:

以下是 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:

这是一个不使用 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