我正在努力变得像熟悉 VB.NET(我工作场所使用的语言)一样熟悉 C#。学习过程中最好的事情之一是,通过学习另一种语言,您往往会更多地了解您的主要语言——像这样的小问题会弹出:
根据我发现的来源和过去的经验,VB.NET 中声明为 WithEvents 的字段能够引发事件。我知道 C# 没有直接等效项——但我的问题是:VB.NET 中没有 this 关键字的字段不能引发事件,有没有办法在 C# 中创建同样的行为? VB 编译器是否简单地阻止这些对象处理它们的事件(同时实际上允许它们像往常一样引发事件)?
我只是好奇;我对这个问题没有任何特定的应用......
最佳答案
省略 WithEvents 不会阻止成员引发事件。它只是阻止您在他们的事件中使用“handles”关键字。
这是 WithEvents 的典型用法:
Class C1
Public WithEvents ev As New EventThrower()
Public Sub catcher() Handles ev.event
Debug.print("Event")
End Sub
End Class
这是一个不使用 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
关于c# - VB.NET WithEvents 关键字行为 - VB.NET 编译器限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/840691/