本文介绍了你需要QUOT&;&无线化QUOT;匿名函数/λ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我的理解是,任何事件处理程序在C#中接线需未连接的这样。 对象myObject的=新的对象(); myObject.Event + =事件处理程序; //有线 myObject.Event - = EventHandler的; // Unwired公司 但你需要无线化下面的代码?如果是这样,怎么 对象myObject的=新的对象()?; myObject.Event + =(对象发件人,EventArgs的E)=> {}; //有线 myObject.Event - = ????? //无线化?怎么样? 我的假设是不? 解决方案 是的,你需要(*),你需要做的是这样的: 对象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; //WiredmyObject.Event -= EventHandler; //UnwiredBut do you need to unwire the following code? and if so, how?Object myObject = new Object();myObject.Event += (object sender, EventArgs e) => { }; //WiredmyObject.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; //WiredmyObject.Event -= handler; //UnwiredSee 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 bulbsNow, 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;匿名函数/λ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-21 02:27