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

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

问题描述

我想知道这是否真的有效?

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:

如何订阅和取消订阅活动

特别注意:


如果您不必取消订阅[sic]
一个事件后,你可以使用
加分运算符(+ =)到
附加一个匿名方法到
事件。

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.

还有:


重要的是要注意到你
不容易如果您使用匿名
函数订阅,则取消订阅
事件。在这种情况下,要
取消订阅,需要返回
您订阅该事件的代码,必须将
存入代理
变量中的
匿名方法,然后将代理添加到
事件。一般来说,我们建议您不要使用匿名
函数
来订阅事件,如果
,您将不得不从
取消订阅$ b $以后的某个事件b代码。

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天全站免登陆