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

2020-03-24 05:30发布

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);

4条回答
▲ chillily
2楼-- · 2020-03-24 05:43

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.

查看更多
霸刀☆藐视天下
3楼-- · 2020-03-24 05:47

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.

查看更多
贪生不怕死
4楼-- · 2020-03-24 05:48

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;
查看更多
成全新的幸福
5楼-- · 2020-03-24 05:57

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

查看更多
登录 后发表回答