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

2019-01-01 11:30发布

问题:

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.

回答1:

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.



回答2:

[object].[event] += anEvent;

is just syntactic sugar for -

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


回答3:

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