繁体   English   中英

使用传递的参数附加方法后,分离事件处理程序

[英]Detach event handler after attaching method with passed parameter

我需要将参数(在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;

原因是两个代表不相等

  // You add one delegate instance 
  _map.MouseLeftButtonUp += (sender, e) => _map_MouseLeftButtonUp2(sender, e, showResultsWindow);

  // ..And try to remove another one (not previous!) That's why the first delegate remains unremoved
  _map.MouseLeftButtonUp += (sender, e) => _map_MouseLeftButtonUp2(sender, e, showResultsWindow);

你可以说服自己

  var x = (sender, e) => _map_MouseLeftButtonUp2(sender, e, showResultsWindow);
  var y = (sender, e) => _map_MouseLeftButtonUp2(sender, e, showResultsWindow);

  if (Object.Equals(x, y)) { // <- You expected this behaviour
    ...
  }
  else { // <- Alas, this is a real situation: x != y
    ...
  }

出现这种现象的原因是,当不重写Object.Equals时(如果不是委托,则不是),Object.Equals就像Object.RefrenceEquals一样,它检查实例的引用(地址)。 当然,x和y的地址以及两个委托人都不同

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM