开发者

AddHandler vs. Handles - what is the difference?

I understood that H开发者_Python百科andles is only one way to add in constructor the AddHandler, but in general are these two are equivalent?


There is some difference in exactly when the event handler is attached, and what is going on around it. For instance, when using WithEvents and Handles, the compiler will emit code that wraps access to the variable holding the instance that exposes the event in a property, and inside the property setter it will detach the event handler from the previous instance (if any), and then attach the event handler to the new instance (if any).

This means that if you take the following code samples, the access to mm will behave differently:

' 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

In the WithEvents case, mm = New SomeClass() will in fact call a property setter, and Dim nn As SomeClass = mm will fetch the value from a property getter, while in the second case, there will be no property created for the value, but the code will access the field directly.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜