C# 删除事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1486214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# removing an event handler
提问by Sharun
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?
我已经这样做了一段时间,但我没有注意到new
每次删除事件处理程序时我都在使用 a 。我应该创建一个新对象吗?
Basically is there a difference between 1 and 2?
基本上1和2之间有区别吗?
ethernetdevice.PcapOnPacketArrival -= new SharpPcap.PacketArrivalEvent(ArrivalResponseHandler);
ethernetdevice.PcapOnPacketArrival -= ArrivalResponseHandler;
ethernetdevice.PcapOnPacketArrival -= new SharpPcap.PacketArrivalEvent(ArrivalResponseHandler);
ethernetdevice.PcapOnPacketArrival -= ArrivalResponseHandler;
EDIT: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.
具有相同目标、方法和调用列表的相同类型的两个委托被认为是相等的。
采纳答案by Christian Hayter
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.
1 和 2 之间没有区别,因为 2 是 1 的语法糖。只有当 2 引用类级委托实例字段而不是实际方法名称时,编译的 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.
就运行时发生的情况而言,事件Remove
方法似乎并不关心传递给它的委托实例是否与传递给该Add
方法的委托实例相同。我不记得为什么会这样,但我猜想委托实例总是被实习的。
EDIT: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. :-)
编辑:Jon Skeet 说事件Remove
方法使用值相等 ( Delegate.Equals
) 来确定从列表中删除哪个委托,而不是实习 + 引用相等。相同的最终结果,不同的方法。:-)
回答by Adam Maras
The second version is equivalent to the first; it just uses a shorter syntax. This was implemented in C# 2.0
第二个版本等同于第一个;它只是使用较短的语法。这是在 C# 2.0 中实现的