C# removing an event handler(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?
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# 删除事件处理程序
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
