What is the difference between two ways of using d

2019-08-09 03:40发布

I wonder that there are two ways of using delegates in C#, with "new" keyword and without:

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?

P.S. 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:

        this.button1.Click += new System.EventHandler(this.button1_Click);
        this.button1.Click += this.button1_Click;

标签: c# delegates
1条回答
够拽才男人
2楼-- · 2019-08-09 03:51

Is there any difference?

No. Both forms compile to the exact same IL.

P.S. I noticed that visual studio form designer generates code with "new" keyword (for events)

In older versions of C#, explicitly instantiating the delegate was required. C# 2 added delegate inference, which allows you to assign a method group to a delegate (or use with an event) directly. The designers still choose the original form, which was required prior to C# 2.0, but is still valid.

查看更多
登录 后发表回答