添加和删​​除匿名事件处理程序 [英] Adding and Removing Anonymous Event Handler

查看:119
本文介绍了添加和删​​除匿名事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在想,如果这个实际工作?

I was wondering if this actually worked ?

private void RegisterKeyChanged(T item) 
{
    item.OnKeyChanged += (o, k) => ChangeItemKey((T)o, k);
}

private void UnRegisterKeyChanged(T item) 
{
    item.OnKeyChanged -= (o, k) => ChangeItemKey((T)o, k);
}

如何编译器知道事件处理程序是一样的吗?这是甚至建议?

How does the compiler know that the event handlers are the same ? Is this even recommended?

推荐答案

这里有一个MSDN页面,谈到这一点:

There's an MSDN page that talks about this:

如何订阅和退订事件

请特别注意:

如果您将不必退订[原文]
  事件后,您可以使用
  除了赋值运算符(+ =)来
  附加一个匿名方法的
  事件。

If you will not have to unsubscribe to [sic] an event later, you can use the addition assignment operator (+=) to attach an anonymous method to the event.

和也:

要注意到你是很重要的
  不能轻易地从退订
  事件如果你使用一个匿名
  功能订阅它。至
  退订在这种情况下,它是
  要回到code其中
  您订阅的情况下,存储
  在一个委托匿名方法
  变量,然后将该委托添加到
  事件 。在一般情况下,我们建议
  您不要使用匿名
  功能,订阅事件,如果
  你将不得不取消订阅
  在以后的某个点的情况下你
  code。

It is important to notice that you cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, it is necessary to go back to the code where you subscribe to the event, store the anonymous method in a delegate variable, and then add the delegate to the event . In general, we recommend that you do not use anonymous functions to subscribe to events if you will have to unsubscribe from the event at some later point in your code.

这篇关于添加和删​​除匿名事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆