VB.NET RemoveHandler&匿名方法 [英] VB.NET RemoveHandler & Anonymous Methods
问题描述
如何将 RemoveHandler
与匿名方法一起使用?
How do I use RemoveHandler
with anonymous methods?
这是我为<$添加处理程序的方式 MyClass
类的c $ c> MyEvent 事件:
This is how I add a handler for MyEvent
event of the class MyClass
:
AddHandler MyClass.MyEvent, Sub()
'...
End Sub
然后如何使用 RemoveHandler
删除 MyEvent
事件的处理程序?
How do I then use RemoveHandler
to remove the handler for the MyEvent
event?
推荐答案
通常,如果您需要退订该事件,建议不要使用像这样的lambda,而应使用标准方法
In general, if you need to unsubscribe from the event, I would recommend not using a lambda like this, and instead use a standard method.
话虽如此,您仍然可以使用匿名方法,但是需要为取消订阅存储对它的引用。如果必须取消订阅匿名方法,则至少应将委托存储在变量中,以便以后将其删除:
That being said, you can still use the anonymous method, but you need to store a reference to it for the unsubscription. If you must unsubscribe an anonymous method, at a minimum, you should store the delegate in a variable to remove it later:
Dim subscription = Sub()
' ...
End Sub
AddHandler MyClass.MyEvent, subscription
' Later
RemoveHandler MyClass.MyEvent, subscription
这篇关于VB.NET RemoveHandler&匿名方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!