C# why shall I use “new” keyword when subscribing for an event?

前端 未结 4 1564
长情又很酷
长情又很酷 2021-01-14 01:23

What is the difference between following 2 ways of subscribing for an event?

receiver.ConfigChanged += Config_ConfigChanged;

receiver.ConfigChanged += new E         


        
相关标签:
4条回答
  • 2021-01-14 01:59

    The verbose way works in all versions of C#, the short way only in C# 2 and later. So I see no reason to use the long way nowadays.

    There are some situations where you still need to use new DelegateType(methodGroup), but event subscribing isn't one of them. These situations usually involve generic type inference or method overloading.

    Unsubscribing will work either way since it is based on value equality, not referential equality. If I recall correctly both the implicit conversion from a method group and the explicit new get translated to the same IL code. The implicit conversion is just syntax sugar.

    0 讨论(0)
  • 2021-01-14 01:59

    Ok so

    receiver.ConfigChanged -= Config_ConfigChanged;
    

    will clear out all event handlers that refer to that method.

    var eventHandler = new EventHandler(Config_ConfigChanged); 
    
    receiver.ConfigChanged += eventHandler;
    receiver.ConfigChanged += new EventHandler(Config_ConfigChanged); 
    
    receiver -= eventHandler;
    

    will only clear out the one eventHandler.

    You use the verbose way if you don't care about tracking the handler.

    0 讨论(0)
  • 2021-01-14 02:05

    Visual Studio's TAB event auto-complete always defaults to the .Net 1.0 way of doing things regardless of what edition of the framework you are using. You may find some people who are used to reading the older way of doing things. I only came across the less verbose way through using Resharper!

    Here's an MSDN article on event subscription - it says exactly what @CodeInChaos just confirmed: http://msdn.microsoft.com/en-us/library/ms366768%28v=vs.80%29.aspx

    0 讨论(0)
  • 2021-01-14 02:25

    Correct me if i'm wrong, but i don't know if this works

    receiver.ConfigChanged += new EventHandler(Config_ConfigChanged);
    receiver.ConfigChanged -= new EventHandler(Config_ConfigChanged);
    

    Since these are 2 different instances I think this would

    var configChanged = new EventHandler(Config_ConfigChanged);
    receiver.ConfigChanged += configChanged;
    receiver.ConfigChanged -= configChanged;
    

    But then again, why not just use

    receiver.ConfigChanged += Config_ConfigChanged;
    receiver.ConfigChanged -= Config_ConfigChanged;
    
    0 讨论(0)
提交回复
热议问题