Should I Create a New Delegate Instance?

2019-01-26 09:55发布

问题:

What are the implications of doing this...

this.myButton.Click += new EventHandler(this.myButton_Clicked);

...versus this?

this.myButton.Click += this.myButton_Clicked;

I suspect that the compiler is creating a new instance for me in the second example. I'm sure this is a bit of a newbie question, but Google didn't turn up anything. Can anyone give me some insight?

回答1:

The 2nd syntax is a shortcut for the 1st one introduced in C# 2.0.

http://www.developer.com/net/csharp/article.php/3103031/Working-with-Delegates-Made-Easier-with-C-20.htm



回答2:

Yes, the second version makes the compiler create an implicit delegate, much like you can specify this.MyMethod instead of new Action(this.MyMethod) or new Action(() => this.MyMethod()).



标签: c# delegates