C# why shall I use quot;newquot; keyword when subscribing for an event?(C# 为什么我要使用“new?订阅事件时的关键字?)
问题描述
以下两种订阅事件的方式有什么区别?
What is the difference between following 2 ways of subscribing for an event?
receiver.ConfigChanged += Config_ConfigChanged;
receiver.ConfigChanged += new EventHandler(Config_ConfigChanged);
似乎两者的工作方式相同,但如果是这样,使用第二个有什么意义?
It seems that both of them work the same way but if so, what is the point of using the second one?
退订怎么办,以下两种方法也一样吗?
What about unsubscribing, will both following methods work also the same way?
receiver.ConfigChanged -= Config_ConfigChanged;
receiver.ConfigChanged -= new EventHandler(Config_ConfigChanged);
推荐答案
verbose 方式适用于所有 C# 版本,short 方式仅适用于 C# 2 及更高版本.所以我认为现在没有理由使用 long way.
The verbose way works in all versions of C#, the short way only in C# 2 and later. So I see no reason to use the long way nowadays.
在某些情况下,您仍然需要使用 new DelegateType(methodGroup)
,但事件订阅不是其中之一.这些情况通常涉及泛型类型推断或方法重载.
There are some situations where you still need to use new DelegateType(methodGroup)
, but event subscribing isn't one of them. These situations usually involve generic type inference or method overloading.
退订会以任何一种方式起作用,因为它基于值相等,而不是引用相等.如果我没记错的话,来自方法组的隐式转换和显式 new
都会被翻译成相同的 IL 代码.隐式转换只是语法糖.
Unsubscribing will work either way since it is based on value equality, not referential equality. If I recall correctly both the implicit conversion from a method group and the explicit new
get translated to the same IL code. The implicit conversion is just syntax sugar.
这篇关于C# 为什么我要使用“new"?订阅事件时的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 为什么我要使用“new"?订阅事件时的关键字?


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01