Are explicit encapsulating delegates still preferred for events in C#?
Style question.
The C# 1.0 way to subscribe to a开发者_如何学Pythonn event is to use an explicit encapsulating delegate:
publisher.RaiseCustomEvent += new CustomEventHandler(HandleCustomEvent);
In C# 2.0 they added a simpler syntax:
publisher.RaiseCustomEvent += HandleCustomEvent;
In Visual Studio 2010 (tested with a .NET 3.5 project) typing
"myObject.SomeEvent +="
brings up the option to hit tab to fill in the explicit delegate. Furthermore, code created with the WinForms designer always uses explicit delegates.
I understand the value in being explicit, but not at the sacrifice of readability. Given that the new syntax is much simpler/cleaner/readable and has been around since 2006, why does Visual Studio push you so hard into using the old syntax? Is it still the preferred syntax?
For the designer code, it should stick with the explicit delegate creation. Both methods (implicitly-typed delegates and explicitly-typed delegates) result in the same IL; the implicit typing is just a language feature in C#, so there's no particular reason for the designer to try to take advantage of them.
As for the typeahead feature when attaching to an event, I have no explanation for that. The only time (I'm aware of) that requires explicit delegate creation is when the target is of type Delegate
(meaning that it has no formal signature). Since you can only declare an event that's of a specific delegate type, I see nothing other than choosing to prioritize other IDE features above this as a reason for this to remain.
There's no good reason. I always remove them. Suit yourself, though I agree with any tendency you have to remove them!
精彩评论