C# 为什么我要使用“new"?订阅事件时的关键字?

C# why shall I use quot;newquot; keyword when subscribing for an event?(C# 为什么我要使用“new?订阅事件时的关键字?)
本文介绍了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"?订阅事件时的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)