你需要“不知道”吗?一个匿名函数/ lambda [英] Do you need to "unwire" an anonymous function/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 eventBlackOut
. - You have a class
LightBulb
that will be on, as long as there is power. It has a methodConnectToPowerSource
. This method subscribes to theBlackOut
event of the suppliedPowerSource
. - You have a collection that contains the light bulbs
现在,从列表中删除灯泡不会使其收集垃圾,因为 PowerSource
仍然在 BlackOut $ c中持有对
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屋!