Is there a benefit to explicit use of “new EventHandler” declaration?

前端 未结 4 1082
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 04:28

In assigning event handlers to something like a context MenuItem, for instance, there are two acceptable syntaxes:

MenuItem item = new MenuItem(         


        
4条回答
  •  既然无缘
    2021-01-12 05:16

    The only time when this is useful is if it would otherwise be ambiguous - for example, if it was MenuItem(string, Delegate) - of if there were multiple equally matching overloads that would match the signature. This also includes var syntax (shown below) and generic type inference (not shown):

    EventHandler handler = SomeMethod; // fine
    EventHandler handler = new EventHandler(SomeMethod); // fine
    var handler = new EventHandler(SomeMethod); // fine
    var handler = (EventHandler)SomeMethod; // fine
    var handler = SomeMethod; // not fine
    

    In all other cases, it is redundant and is unnecessary in any compiler from 2.0 onwards.

提交回复
热议问题