我知道这Handles
只是在构造函数中添加的一种方法AddHandler
,但总的来说这两者是等价的吗?
问问题
2104 次
2 回答
3
附加事件处理程序的确切时间以及周围发生的事情存在一些差异。例如,当使用WithEvents
and时Handles
,编译器将发出代码来包装对持有实例的变量的访问,该实例在属性中公开事件,并且在属性设置器中,它将事件处理程序与前一个实例(如果有的话)分离,并且然后将事件处理程序附加到新实例(如果有)。
这意味着,如果您采用以下代码示例,访问的mm
行为将有所不同:
' WithEvents approach '
Dim WithEvents mm As SomeClass
Sub Main()
mm = New SomeClass()
Dim nn As SomeClass = mm
End Sub
' Other approach '
Dim mm As SomeClass
Sub Main()
mm = New SomeClass()
Dim nn As SomeClass = mm
End Sub
在这种WithEvents
情况下,mm = New SomeClass()
实际上将调用属性设置器,并Dim nn As SomeClass = mm
从属性获取器中获取值,而在第二种情况下,不会为该值创建属性,但代码将直接访问该字段。
于 2010-01-18T11:22:46.027 回答
0
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'this
AddHandler Button2.Click, AddressOf Button2_Click
'now Button2_Click looks like this
'Private Sub Button2_Click(ByVal sender As System.Object, _
'ByVal e As System.EventArgs) Handles Button2.Click
End Sub
于 2010-01-18T22:08:20.053 回答