What is the difference between different ways of attaching\detaching event handlers in C#

*爱你&永不变心* 提交于 2019-12-22 10:58:23

问题


There are two parts to my question -

Firstly we can attach event handlers in following two ways -

myObject.MyEvent += new EventHandler(MyHandler);

myObject.MyEvent += MyHandler;

As per my understanding these two are equivalent. In the second case the C# compiler does the job of creating a delegate instance from the appropriate overload from the specified method group. Is this correct?

Secondly, is there any difference between the two corresponding styles of detaching the handler? If yes then what is it?

 myObject.MyEvent -= new EventHandler(MyHandler);

 myObject.MyEvent -= MyHandler;

回答1:


There is no difference in the IL code that is generated - as you mentioned. C# compiler creates a handler anyway.

In the removing also, there is no difference.




回答2:


They are identical, unless you are in c# 1.2 where only the first compiles.



来源:https://stackoverflow.com/questions/4360451/what-is-the-difference-between-different-ways-of-attaching-detaching-event-handl

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