是否有利于明确使用"新的事件处理程序"宣言? [英] Is there a benefit to explicit use of "new EventHandler" declaration?
问题描述
在指定的事件处理程序,以类似上下文菜单项
,例如,有两种可接受的语法:
In assigning event handlers to something like a context MenuItem
, for instance, there are two acceptable syntaxes:
MenuItem item = new MenuItem("Open Image", btnOpenImage_Click);
...和...
...and...
MenuItem item = new MenuItem("Open Image", new EventHandler(btnOpenImage_Click));
我也注意到了同样的似乎适用于这样的:
I also note that the same appears to apply to this:
listView.ItemClick += listView_ItemClick;
...和...
...and...
listView.ItemClick += new ItemClickEventHandler(listView_ItemClick);
有什么特别的优势,为第二(明确)在第一个?或者这更多的是一种风格上的问题吗?
Is there any particular advantage for the second (explicit) over the first? Or is this more of a stylistic question?
推荐答案
在C#1.0,你别无选择,只能明确定义的委托类型和目标。
In C# 1.0 you had no choice but to explicitly define the delegate type and the target.
由于C#2.0编译器可以让你的前preSS自己在一个更简洁的方式从一个方法组的隐式转换为兼容的委托类型的方式。这真的只是语法糖。
Since C# 2.0 the compiler allows you to express yourself in a more succinct manner by means of an implicit conversion from a method group to a compatible delegate type. It's really just syntactic sugar.
有时候,你有没有选择,只能使用冗长的语法是否正确超载不能从方法组解决因歧义。
Sometimes you have no choice but to use the long-winded syntax if the correct overload cannot be resolved from the method group due to an ambiguity.
这篇关于是否有利于明确使用"新的事件处理程序"宣言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!