C# why shall I use “new” keyword when subscribing

2020-03-24 05:29发布

问题:

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

receiver.ConfigChanged += Config_ConfigChanged;

receiver.ConfigChanged += new EventHandler(Config_ConfigChanged);

It seems that both of them work the same way but if so, what is the point of using the second one?

What about unsubscribing, will both following methods work also the same way?

receiver.ConfigChanged -= Config_ConfigChanged;

receiver.ConfigChanged -= new EventHandler(Config_ConfigChanged);

回答1:

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.



回答2:

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



回答3:

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;


回答4:

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.