C#: Difference between #39; += anEvent#39; and #39; += new EventHandler(anEvent)#39;(C#:“+= anEvent和“+= new EventHandler(anEvent)之间的区别)
问题描述
获取以下代码:
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);
[更新]
显然,两者没有区别……前者只是后者的语法糖.
Apparently, there is no difference between the two...the former is just syntactic sugar of the latter.
推荐答案
没有区别.在您的第一个示例中,编译器将自动推断您要实例化的委托.在第二个示例中,您明确定义了委托.
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.
在 C# 2.0 中添加了委托推理.因此,对于 C# 1.0 项目,第二个示例是您唯一的选择.对于 2.0 项目,使用推理的第一个示例是我更喜欢在代码库中使用和查看的示例 - 因为它更简洁.
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#:“+= anEvent"和“+= new EventHandler(anEvent)"之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#:“+= anEvent"和“+= new EventHandler(anEvent)"之间的区别


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