What is the difference between different ways of a

2019-05-18 10:41发布

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;

2条回答
做个烂人
2楼-- · 2019-05-18 11:22

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.

查看更多
女痞
3楼-- · 2019-05-18 11:22

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

查看更多
登录 后发表回答