简体   繁体   中英

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

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;

它们是相同的,除非你在c#1.2中只有第一个编译。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM