VB.NET RemoveHandler & Anonymous Methods

梦想的初衷 提交于 2019-12-17 18:51:36

问题


How do I use RemoveHandler with anonymous methods?

This is how I add a handler for MyEvent event of the class MyClass:

AddHandler MyClass.MyEvent, Sub()
                                '...
                            End Sub

How do I then use RemoveHandler to remove the handler for the MyEvent event?


回答1:


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


来源:https://stackoverflow.com/questions/7447168/vb-net-removehandler-anonymous-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!