Differences in assigning C# event handlers?(分配 C# 事件处理程序的区别?)
问题描述
我总是分配这样的事件处理程序,由 Intellisense 自动完成引导.
I've always assigned event handlers like this, guided by Intellisense auto-completion.
RangeSelector.RangeChanged += new EventHandler(RangeSelector_RangeChanged);
我最近注意到我的一位同事这样做.
I've recently noticed one of my colleagues does it this way.
RangeSelector.RangeChanged += RangeSelector_RangeChanged;
这两种方法在语法上都是正确的,编译和行为都符合预期.
Both methods are syntactically correct, compile and behave as expected.
这些方法有什么区别、优点或缺点.它们会产生相同的 IL 代码还是我需要注意一些细微的差异?
What are the differences, benefits or disadvantages of these methods. Do they result in the same IL code or is there some subtle difference that I need to be aware of?
推荐答案
这些方法有什么区别、优点或缺点.
What are the differences, benefits or disadvantages of these methods.
第二种方法较新,即仅从 C# 2.0(我相信)开始支持它,它添加了从方法组(即方法名称)到委托的自动转换.因此编译器添加了构造函数调用,而第二种方法只是第一种方法的语法糖.
The second method is newer, i.e. it is only supported since C# 2.0 (I believe), which added an automatic conversion from a method group (i.e. a method name) to a delegate. The constructor call is thus added by the compiler and the second method is just syntactic sugar for the first one.
因此,两者之间没有其他区别.
Because of that, there are no other differences between the two.
由于第二种方法与第一种方法相同,语法较少,因此应该首选.
Since the second method does the same as the first, with less syntax, it should be preferred.
这篇关于分配 C# 事件处理程序的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:分配 C# 事件处理程序的区别?


基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01