您是否需要“拆线"?匿名函数/lambda [英] Do you need to "unwire" an anonymous function/lambda

查看:36
本文介绍了您是否需要“拆线"?匿名函数/lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,在 C# 中连接的任何事件处理程序都需要取消连接.

My understanding is that any event handlers wired up in C# need to be unwired as such.

Object myObject = new Object();
myObject.Event += EventHandler; //Wired
myObject.Event -= EventHandler; //Unwired

但是下面的代码需要拆线吗?如果是这样,如何?

But do you need to unwire the following code? and if so, how?

Object myObject = new Object();
myObject.Event += (object sender, EventArgs e) => { }; //Wired
myObject.Event -= ????? //Unwire? How?

我的假设是否定的?

推荐答案

是的,你需要 (*) 并且你需要这样做:

Yes, you need to (*) and you need to do it like this:

Object myObject = new Object();
EventHandler handler = (object sender, EventArgs e) => { };
myObject.Event += handler; //Wired
myObject.Event -= handler; //Unwired

有关说明,请参阅此处.

(*)
由于垃圾收集,您不需要这样做.如果您不想让事件再调用您的处理程序,您需要这样做.

(*)
You don't need to do it because of garbage collection. You need to do it, if you don't want the event to call your handler any more.

更新:
澄清一下:
您想要取消连接事件处理程序的唯一原因是定义事件处理程序的对象可以被垃圾收集.
想想下面的例子:

UPDATE:
To clarify a bit:
The only reason, why you want to unwire an event handler is that the object defining the event handler can be garbage collected.
Think about the following example:

  • 您有一个带有事件 BlackOut 的类 PowerSource.
  • 您有一个 LightBulb 类,只要有电,它就会亮起.它有一个方法ConnectToPowerSource.此方法订阅所提供的 PowerSourceBlackOut 事件.
  • 您有一个包含灯泡的集合
  • You have a class PowerSource with an event BlackOut.
  • You have a class LightBulb that will be on, as long as there is power. It has a method ConnectToPowerSource. This method subscribes to the BlackOut event of the supplied PowerSource.
  • You have a collection that contains the light bulbs

现在,简单地从列表中删除一个灯泡不会让它被垃圾回收,因为 PowerSource 仍然在它的 LightBulb 实例中持有一个引用code>BlackOut 事件.只有在从 BlackOut 事件中注销 LightBulb 后,LightBulb 才会被垃圾收集.

Now, simply removing a light bulb from the list will not make it get garbage collected, because the PowerSource is still holding a reference to the LightBulb instance in its BlackOut event. Only after unregistering the LightBulb from the BlackOut event will make the LightBulb get garbage collected.

这篇关于您是否需要“拆线"?匿名函数/lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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