简体   繁体   中英

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:

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:

        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.

PS 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM