你需要QUOT&;&无线化QUOT;匿名函数/λ [英] Do you need to "unwire" an anonymous function/lambda

查看:117
本文介绍了你需要QUOT&;&无线化QUOT;匿名函数/λ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,任何事件处理程序在C#中接线需未连接的这样。

 对象myObject的=新的对象(); 
myObject.Event + =事件处理程序; //有线
myObject.Event - = EventHandler的; // Unwired公司



但你需要无线化下面的代码?如果是这样,怎么

 对象myObject的=新的对象()?; 
myObject.Event + =(对象发件人,EventArgs的E)=> {}; //有线
myObject.Event - = ????? //无线化?怎么样?

我的假设是不?


< DIV CLASS =h2_lin>解决方案

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

 对象myObject的=新的对象(); 
事件处理程序处理程序=(对象发件人,EventArgs的E)=> {};
myObject.Event + =处理程序; //有线
myObject.Event - =处理程序; // Unwired公司

请参阅的这里解释。



(*)结果
你不需要这么做,因为垃圾收集。你需要做的是,如果你不希望事件调用处理更多的做



更新:结果
要澄清一下:结果
的唯一原因,你为什么要无线化的事件处理程序是定义事件处理程序的对象可以被垃圾收集结果
想想下面的例子:




  • 您有一个类 PowerSource 与事件停电

  • 您有一个类灯泡,这将是对的,只要有电。它有一个方法 ConnectToPowerSource 。这种方法订阅提供的 PowerSource 停电事件。

  • 您有一个包含灯泡集合



现在,只需从列表中删除一个灯泡不会使它得到垃圾收集,因为在 PowerSource 仍持有其停电灯泡实例的引用$ 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?

My assumption is no?

解决方案

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

See here for an explanation.

(*)
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:

  • 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

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.

这篇关于你需要QUOT&;&无线化QUOT;匿名函数/λ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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