你需要“不知道”吗?一个匿名函数/ lambda [英] Do you need to "unwire" an anonymous function/lambda

查看:125
本文介绍了你需要“不知道”吗?一个匿名函数/ 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:


  • 您有一个类 PowerSource 与事件 BlackOut

  • 只要有电源,您将会有一个课程 LightBulb 。它有一个方法 ConnectToPowerSource 。此方法订阅所提供的 PowerSource BlackOut 事件。

  • 您有一个包含灯泡的集合

  • 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 仍然在 BlackOut LightBulb 实例的引用$ c>事件。只有在从 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天全站免登陆