What is the difference between these two syntaxes

2019-02-26 01:02发布

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?

4条回答
Emotional °昔
2楼-- · 2019-02-26 01:14

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楼-- · 2019-02-26 01:15

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.

查看更多
再贱就再见
4楼-- · 2019-02-26 01:26

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

查看更多
Root(大扎)
5楼-- · 2019-02-26 01:30

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

查看更多
登录 后发表回答