使用传递参数附加方法后分离事件处理程序 [英] Detach event handler after attaching method with passed parameter
问题描述
我需要将参数(在C#中)传递给一个事件处理程序,然后可以分离事件处理程序。
I need to pass a parameter (in C#) to an event handler and then be able to detach the event handler.
我附加事件处理程序并传递参数:
I attach the event handler and pass the parameter:
_map.MouseLeftButtonUp += (sender, e) => _map_MouseLeftButtonUp2(sender, e, showResultsWindow);
事件按预期调用。我尝试分离事件处理程序:
The event is called as expected. I try to detach the event handler:
_map.MouseLeftButtonUp -= (sender, e) => _map_MouseLeftButtonUp2(sender, e, showResultsWindow);
代码执行没有错误,但似乎没有分离。
The code executes without error, but does not seem to detach.
如果我附加事件处理程序更传统的方式(不传递参数):
If I attach the event handler the more conventional way (without passing a parameter):
_map.MouseLeftButtonUp+=_map_MouseLeftButtonUp;
并分离
_map.MouseLeftButtonUp -= _map_MouseLeftButtonUp;
一切正常工作
事件处理程序(通过更传统的方式获取参数)
Detaching the event handler (that takes a parameter) via the more conventional way
_map.MouseLeftButtonUp -= _map_MouseLeftButtonUp2;
给我一个错误,表示代表不匹配(这是有道理的)
gives me an error saying the delegates don't match (which makes sense)
所以我的问题是:为什么当我传递一个参数时,事件处理程序不是真正的分离,有没有办法规避这个问题。
So my question is: Why is the event handler not really being detached when I pass a parameter, and is there a way to circumvent this problem.
推荐答案
当您创建一个lambda(匿名)功能时,您实际上每次都创建一个新功能。
When you create a lambda (anonymous) function, you're actually creating a new function each time.
你的前两行不起作用的原因是因为它们是两个完全不同的功能,只是碰巧做同样的事情。正确的方法是将您的订单和取消订阅功能,如您已经想出的那样。
The reason your first two lines don't work is because they are two completely different functions that just happen to do the same thing. The correct way to detach would be to have subscribe and unsubscribe from a function, as you've already figured out.
另一种可能不值得的是将你的lambda保存到变量中。
An alternative, that's probably not worth it, is to save your lambda to a variable.
Action<object, MouseButtonEventArgs> myEventMethod = (sender, e) => _map_MouseLeftButtonUp2(sender, e, showResultsWindow);
_map.MouseLeftButtonUp += myEventMethod;
// ...
_map.MouseLeftButtonUp -= myEventMethod;
这篇关于使用传递参数附加方法后分离事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!