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"?订阅事件时的关键字?


基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01