C#: what's the difference between SomeEvent += Method and SomeEvent += new Delegate(Method) [duplicate]

别等时光非礼了梦想. 提交于 2019-12-19 18:25:03

问题


Possible Duplicate:
Should I Create a New Delegate Instance?

Hi, I've tried searching for the answer to this, but don't really know what terms to search for, and none of the site-suggested questions are relevant. I'm sure this must have been answered before though.

Basically, can somebody tell me what's the difference between these two lines in C#:

SomeEvent += SomeMethod
SomeEvent += new SomeDelegate(SomeMethod)

For example:

DataContextChanged += App_DataContextChanged;
DataContextChanged += new DependencyPropertyChangedEventHandler(App_DataContextChanged);

They both seem to do the same thing.


回答1:


They are the same. The second variant is just a shorthand for the first called Method group conversion.

Simply put, the compiler infers what the type of the delegate is by using the delegate type of the event itself. This was introduced in C#2.0 if I'm not mistaken.




回答2:


they do the same thing. The variation

SomeEvent += new SomeDelegate(SomeMethod)

was the only way to write it in C# 1.0, 1.1 . Since 2.0 you can write the other alternative as a simplification.




回答3:


Both are same.

SomeEvent += new SomeDelegate(SomeMethod)

mentions what happens under the hood i.e SomeDelegate constructor is called to create a instance of the object.



来源:https://stackoverflow.com/questions/4679369/c-whats-the-difference-between-someevent-method-and-someevent-new-deleg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!