C# 删除事件处理程序

C# removing an event handler(C# 删除事件处理程序)

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

问题描述

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

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;

好的,这是重复的.对于那个很抱歉.答案发布在这里.

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.

就运行时发生的情况而言,事件 Remove 方法似乎并不关心传递给它的委托实例是否与传递给 Add 的委托实例相同 方法.我不记得为什么会这样,但我猜委托实例总是被实习的.

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 说事件 Remove 方法使用值相等 (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# 删除事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C# 删除事件处理程序