AddHandler 与 Handles - 有什么区别?
我了解Handles
只是在构造函数中添加AddHandler
的一种方法 code>,但是一般来说这两个是等价的吗?
I understood that Handles
is only one way to add in constructor the AddHandler
, but in general are these two are equivalent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
附加事件处理程序的确切时间及其周围发生的情况存在一些差异。例如,当使用
WithEvents
和Handles
时,编译器将发出代码,包装对保存在属性中公开事件的实例的变量的访问,并在属性设置器内它将把事件处理程序与前一个实例(如果有)分离,然后将事件处理程序附加到新实例(如果有)。这意味着,如果您采用以下代码示例,对
mm
的访问将表现不同:在
WithEvents
情况下,mm = New SomeClass()
实际上会调用一个属性 setter,而Dim nn As SomeClass = mm
将从属性 getter 中获取值,而在第二种情况下,不会为该值创建任何属性,但是代码将直接访问该字段。There is some difference in exactly when the event handler is attached, and what is going on around it. For instance, when using
WithEvents
andHandles
, 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:In the
WithEvents
case,mm = New SomeClass()
will in fact call a property setter, andDim 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.