[聚合问答] C#: Difference between ' += anEvent' and ' += new EventHandler(anEvent)'

c#,delegates,event-handling 2017-11-30 8 阅读

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个回答

76

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.

2017-11-30
13

[object].[event] += anEvent;

is just syntactic sugar for -

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

2017-11-30
10

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

2017-11-30

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版本等事宜,请你联系站长进行处理。