What is the difference between these two syntaxes

2019-02-26 00:27发布

问题:

Possible Duplicate:
Is there an actual difference in the 2 different ways of attaching event handlers in C#?

I've been seeing a lot of code that looks like this:

foo.Drop += new DragEventHandler(fooHandler);

But in the past, I've always done this:

foo.Drop += fooHandler;

Is there a difference between these two syntaxes? If so, is there any advantage to doing it the long way?

回答1:

The second is shorthand for the first; they will compile to indentical IL.

However, the second syntax is new to C# 2.0; C# 1 only supports the first.



回答2:

They will both result in the same IL.

So, in answer to your question, no - there is no benefit of using the longer version.



回答3:

No difference , since .Net 2 and you can use what is called Method Group Conversion which allow you to Register the method name directly to the event without making a delegate Object



回答4:

They are the same, but in the second example, the compiler uses Method Group conversion to infer the delegate type for you. Syntactic sugar...