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

查看:152
本文介绍了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 - = new SharpPcap.PacketArrivalEvent(ArrivalResponseHandler);

ethernetdevice.PcapOnPacketArrival - = ArrivalResponseHandler;

编辑:
好​​的,这是一个重复的。对于那个很抱歉。
答复发布此处

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

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.

编辑: Jon Skeet说事件删除方法使用值等价( 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天全站免登陆