[英]What is the difference between two ways of using delegates in C# (with new keyword and without)
I wonder that there are two ways of using delegates in C#, with "new" keyword and without: 我想知道有两种在C#中使用委托的方式,带有“ new”关键字,而没有:
delegate void D(string value);
static void Main()
{
D d1 = new D(v => Console.WriteLine(v)); // 1
D d2 = v => Console.WriteLine(v); // 2
d1.Invoke("cat");
d2.Invoke("cat");
Console.ReadLine();
}
Is there any difference? 有什么区别吗?
PS I noticed that visual studio form designer generates code with "new" keyword (for events), but when I remove it (from generated code), it works either: PS我注意到Visual Studio表单设计器使用“ new”关键字(用于事件)生成代码,但是当我将其删除(从生成的代码中)时,它可以工作:
this.button1.Click += new System.EventHandler(this.button1_Click);
this.button1.Click += this.button1_Click;
Is there any difference?
有什么区别吗?
No. Both forms compile to the exact same IL. 不会。两种形式都编译为完全相同的IL。
PS I noticed that visual studio form designer generates code with "new" keyword (for events)
PS我注意到Visual Studio表单设计器会生成带有“ new”关键字的代码(用于事件)
In older versions of C#, explicitly instantiating the delegate was required. 在旧版本的C#中,需要显式实例化委托。 C# 2 added delegate inference , which allows you to assign a method group to a delegate (or use with an event) directly.
C#2添加了委托推断 ,它允许您直接将方法组分配给委托(或与事件一起使用)。 The designers still choose the original form, which was required prior to C# 2.0, but is still valid.
设计人员仍然选择原始形式,这是C#2.0之前所必需的,但仍然有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.