C#:“+= anEvent”和“+= new EventHandler(anEvent)”的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/550703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C#: Difference between ' += anEvent' and ' += new EventHandler(anEvent)'
提问by Andreas Grech
Take the below code:
取下面的代码:
private void anEvent(object sender, EventArgs e) {
//some code
}
What is the difference between the following ?
以下有什么区别?
[object].[event] += anEvent;
//and
[object].[event] += new EventHandler(anEvent);
[UPDATE]
[更新]
Apparently, there is no difference between the two...the former is just syntactic sugar of the latter.
显然,两者之间没有区别……前者只是后者的语法糖。
采纳答案by driis
There is no difference. In your first example, the compiler will automatically infer the delegate you would like to instantiate. In the second example, you explicitly define the delegate.
没有区别。在您的第一个示例中,编译器将自动推断您要实例化的委托。在第二个示例中,您显式定义了委托。
Delegate inference was added in C# 2.0. So for C# 1.0 projects, second example was your only option. For 2.0 projects, the first example using inference is what I would prefer to use and see in the codebase - since it is more concise.
C# 2.0 中添加了委托推理。因此,对于 C# 1.0 项目,第二个示例是您唯一的选择。对于 2.0 项目,使用推理的第一个示例是我更喜欢在代码库中使用和查看的示例 - 因为它更简洁。
回答by Megacan
I don't think there is a difference. The compiler transforms the first into the second.
我不认为有区别。编译器将第一个转换为第二个。
回答by Martin Joná?
[object].[event] += anEvent;
is just syntactic sugar for -
只是语法糖 -
[object].[event] += new EventHandler(anEvent);