问题描述
以下2种方式认购的事件之间的区别是什么?
receiver.ConfigChanged + = Config_ConfigChanged;
receiver.ConfigChanged + =新的EventHandler(Config_ConfigChanged);
看来,两者的工作方式相同,但如果是这样,什么是使用第二个点?
怎么样退订,都将下面的方法也以同样的方式?
receiver.ConfigChanged - = Config_ConfigChanged;
receiver.ConfigChanged - =新的EventHandler(Config_ConfigChanged);
的详细方法适用于所有版本的C#中,只在C#2和后来的一小段路的。所以,我看不出有任何理由使用很长的路要走现在。
有一些情况下,你仍然需要使用新DelegateType(methodGroup)
,但事件订阅是不是其中之一。这些情况通常涉及泛型类型推断或方法的重载。
退订将两种方式工作,因为它是基于价值的平等,而不是指涉平等。如果我没有记错无论是从方法组隐式转换和显式的新
会转换到相同的IL code。隐式转换只是语法糖。
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);
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.
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.
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#为什么我用"新"关键字订阅的事件是什么时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!