我应该实例化一个新的委托或不?或不、实例

2023-09-03 00:35:00 作者:刺人心

我才意识到我可以通过两种方式添加事件处理程序:

I just realized I can add an event handler in two ways:

考虑,像这样的事件处理程序:

Consider an event handler like so:

private void MyEventHandler()
{}

方法1:实例化一个新的委托

Method 1: Instantiate a new delegate

MyObject.MyEvent += new Action(MyEventHandler);

方法2:添加事件处理程序没有实例化一个新的委托

Method 2: Add event handler without instantiating a new delegate

MyObject.MyEvent += MyEventHandler;

是否有应该考虑这两种实现之间有什么区别?

Is there any difference in between these two implementations that should be considered?

推荐答案

没有区别,所产生的IL是一样的。在较短的形式被引入.NET / C#2.0中作为一个方便的功能,尽管Visual Studio中仍然没有对标签完成的第一个表单。

There is no difference, the generated IL is the same. The shorter form was introduced in .net/c# 2.0 as a convenience function, although Visual Studio still does the first form on Tab Completion.

请参阅这个问题了解更多信息。