问题描述
我的理解是,在 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
.此方法订阅所提供的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
仍然在它的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!