我需要将参数(在 C# 中)传递给事件处理程序,然后能够分离事件处理程序。
我附加事件处理程序并传递参数:
_map.MouseLeftButtonUp += (sender, e) => _map_MouseLeftButtonUp2(sender, e, showResultsWindow);
事件按预期调用。我尝试分离事件处理程序:
_map.MouseLeftButtonUp -= (sender, e) => _map_MouseLeftButtonUp2(sender, e, showResultsWindow);
代码执行没有错误,但似乎没有分离。
如果我以更传统的方式附加事件处理程序(不传递参数):
_map.MouseLeftButtonUp+=_map_MouseLeftButtonUp;
并分离
_map.MouseLeftButtonUp -= _map_MouseLeftButtonUp;
一切正常
通过更传统的方式分离事件处理程序(接受参数)
_map.MouseLeftButtonUp -= _map_MouseLeftButtonUp2;
给我一个错误,说代表不匹配(这是有道理的)
所以我的问题是:为什么当我传递一个参数时,事件处理程序并没有真正被分离,有没有办法避免这个问题。
最佳答案
当您创建一个 lambda(匿名)函数时,您实际上每次都在创建一个新函数。
你的前两行不起作用的原因是因为它们是两个完全不同的函数,只是碰巧做同样的事情。正如您已经知道的那样,分离的正确方法是订阅和取消订阅一个函数。
另一种可能不值得的方法是将 lambda 表达式保存到变量中。
Action<object, MouseButtonEventArgs> myEventMethod = (sender, e) => _map_MouseLeftButtonUp2(sender, e, showResultsWindow);
_map.MouseLeftButtonUp += myEventMethod;
// ...
_map.MouseLeftButtonUp -= myEventMethod;
关于c# - 使用传递的参数附加方法后分离事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17995339/