What the purpose/difference in using an event-type constructor
In all examples I can find as well as the automatically generated code i Visual Studio, events are s开发者_JAVA技巧et using the following code:
button1.Click += new System.EventHandler(this.button1_Click);
But I can also write it visually cleaner by omitting the constructor wrapper:
button1.Click += this.button1_Click;
Which also compile fine.
What is the difference between these two? And why is the first one mostly used/preferred?
The second form (implicit conversion from a method group to a delegate type) wasn't supported before C# 2, so any tutorials etc written before 2005 would have used the first form.
Also, IIRC Visual Studio auto-completes the first form. Personally I prefer the second.
The second one is syntactic sugar that expands to the first one, through compiler magic.
The first one might be preferred because the event type isn't hidden from the code, and thus might be easier to read later on, but functionally (and IL-wise) they're the same.
It is removing event handlers that inspired the sugar:
button1.Click -= new System.EventHandler(this.button1_Click);
Using new to remove an event handler? Yes.
Even the full delegate constructor syntax is sugar. A delegate needs a Method and a Target. The target is automatically assigned without you specifying it. It will be "this". A bit unfortunate, it hides the fact that an event subscription adds a reference to your class object that can keep it from being garbage collected. It is explicit in the C++/CLI syntax:
button1->Click += gcnew System::EventHandler(this, &button1_Click);
with the interesting twist that you could actually subscribe an event handling method of another object or class. Not that this gets a lot of use.
精彩评论