C# 为什么我要使用“new"?订阅事件时的关键字? [英] C# why shall I use "new" keyword when subscribing for an event?

查看:31
本文介绍了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"?订阅事件时的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆