C#: Difference between ' += anEvent' and &

2019-01-01 10:56发布

Take the below code:

private void anEvent(object sender, EventArgs e) {
    //some code
}

What is the difference between the following ?

[object].[event] += anEvent;

//and

[object].[event] += new EventHandler(anEvent);

[UPDATE]

Apparently, there is no difference between the two...the former is just syntactic sugar of the latter.

3条回答
像晚风撩人
2楼-- · 2019-01-01 11:39
[object].[event] += anEvent;

is just syntactic sugar for -

[object].[event] += new EventHandler(anEvent);
查看更多
何处买醉
3楼-- · 2019-01-01 11:45

There is no difference. In your first example, the compiler will automatically infer the delegate you would like to instantiate. In the second example, you explicitly define the delegate.

Delegate inference was added in C# 2.0. So for C# 1.0 projects, second example was your only option. For 2.0 projects, the first example using inference is what I would prefer to use and see in the codebase - since it is more concise.

查看更多
后来的你喜欢了谁
4楼-- · 2019-01-01 11:58

I don't think there is a difference. The compiler transforms the first into the second.

查看更多
登录 后发表回答