问题
I've always assigned event handlers like this, guided by Intellisense auto-completion.
RangeSelector.RangeChanged += new EventHandler(RangeSelector_RangeChanged);
I've recently noticed one of my colleagues does it this way.
RangeSelector.RangeChanged += RangeSelector_RangeChanged;
Both methods are syntactically correct, compile and behave as expected.
What are the differences, benefits or disadvantages of these methods. Do they result in the same IL code or is there some subtle difference that I need to be aware of?
回答1:
What are the differences, benefits or disadvantages of these methods.
The second method is newer, i.e. it is only supported since C# 2.0 (I believe), which added an automatic conversion from a method group (i.e. a method name) to a delegate. The constructor call is thus added by the compiler and the second method is just syntactic sugar for the first one.
Because of that, there are no other differences between the two.
Since the second method does the same as the first, with less syntax, it should be preferred.
回答2:
No difference, it results in the same IL.
It's just a way to say the same thing with less code.
回答3:
The result is the same in both cases. But in the latter the C# compiler will infer the EventHandler type from the code, thus saving you a few key strokes.
回答4:
yes, compiler creates the same IL code in both cases, the second case is just syntax sugar
来源:https://stackoverflow.com/questions/1326778/differences-in-assigning-c-sharp-event-handlers