C#中删除的事件处理程序 [英] C# removing an event handler

查看:334
本文介绍了C#中删除的事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经这样做了一段时间,但我还没有注意到,我一直在使用一个每次我删除事件处理程序。我应该要创建一个新的对象?

I've been doing this for a while, but I haven't noticed that I've been using a new each time I remove an event handler. Am I supposed to be creating a new object?

基本上是有1和2之间有区别吗?

Basically is there a difference between 1 and 2?


  1. ethernetdevice.PcapOnPacketArrival - =新SharpPcap.PacketArrivalEvent(ArrivalResponseHandler);

ethernetdevice.PcapOnPacketArrival - = ArrivalResponseHandler;

修改
好​​吧,这是一个重复。对于那个很抱歉。
答案贴 href=\"http://stackoverflow.com/questions/1307607/removing-event-handlers\">。

Okay this is a duplicate. Sorry about that. Answer posted here.

同一类型,具有相同的目标,方法和调用列表的两名代表被认为是相等的。

Two delegates of the same type with the same targets, methods, and invocation lists are considered equal.

推荐答案

有什么区别1和2之间,因为2是语法糖1.只有2条所指的类级别的委托实例字段,而不是实际的方法名称会有在编译的IL的差异。

There is no difference between 1 and 2, because 2 is syntactic sugar for 1. Only if 2 referred to a class-level delegate instance field rather than the actual method name would there be a difference in the compiled IL.

在在运行时会发生什么情况来看,该事件删除方法似乎并不关心传递给它的委托实例是否是同一个的一个传递到添加方法。我不记得了手这是为什么,但我猜想,委托实例总是被拘留

In terms of what happens at runtime, the event Remove method does not seem to care whether or not the delegate instance passed to it is the same one as the one passed to the Add method. I can't remember off-hand why this is, but I would guess that delegate instances are always interned.

编辑:乔恩斯基特说该事件删除方法使用的值相等( Delegate.Equals )来确定从列表中删除其中的代表,而比实习+参考平等。相同的最终结果,不同的方法。 : - )

Jon Skeet says that the event Remove method uses value equality (Delegate.Equals) to determine which delegate to remove from the list, rather than interning + reference equality. Same end result, different method. :-)

这篇关于C#中删除的事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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