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

前端 未结 4 1056
隐瞒了意图╮
隐瞒了意图╮ 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 04:55

    Related to your edit - The adding of handlers isn't really affected by using new or not but there's a slight difference in removing handlers like this

    listView.ItemClick -= listView_ItemClick;
    

    and

    listView.ItemClick -= new ItemClickEventHandler(listView_ItemClick);
    

    albeit unlikely to affect most scenarios. The first version, without the new keyword, is supposedly more efficient.

    There's a detailed explanation in this post but the conclusion is

    So both works but which one should we use? If the events are subscribed/unsubscribed once at the beginning/end like in a typical WinForm application then it hardly matters. However if this is done multiple times then the second approach is preferable as it does less of costly heap allocations and will work faster

    (second approach in that post being the one without the new keyword)

    Having said that it seems like a micro optimization to me so it's unlikely to be a bottleneck in the majority of cases.

    0 讨论(0)
  • 2021-01-12 04:59

    It's syntax for older version of C# compiler (<=1.1). Not needed anymore. Current compilers are sophisticated enough to get it right.

    There's one (little) benefit, sometimes. If you assign event handlers by "+=", the Intellisense autocomplete feature may make writing code a bit faster.

    0 讨论(0)
  • 2021-01-12 05:15

    In C# 1.0 you had no choice but to explicitly define the delegate type and the target.

    Since C# 2.0 the compiler allows you to express yourself in a more succinct manner by means of an implicit conversion from a method group to a compatible delegate type. It's really just syntactic sugar.

    Sometimes you have no choice but to use the long-winded syntax if the correct overload cannot be resolved from the method group due to an ambiguity.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题