Action(arg)和Action.Invoke(arg)之间的区别

时间:2011-10-26 18:19:57

标签: c#

static void Main()
{
    Action<string> myAction = SomeMethod;

    myAction("Hello World");
    myAction.Invoke("Hello World");
}

static void SomeMethod(string someString)
{
    Console.WriteLine(someString);
}

以上的输出是:

Hello World
Hello World

现在我的问题是

  • 调用Action的两种方法有什么区别?

  • 一个比另一个好吗?

  • 何时使用?

谢谢

1 个答案:

答案 0 :(得分:29)

所有委托类型都有编译器生成的Invoke方法 C#允许您将委托本身作为调用此方法的快捷方式调用。

他们都编译到同一个IL:

C#:

Action<string> x = Console.WriteLine;
x("1");
x.Invoke("2");

IL:

IL_0000:  ldnull      
IL_0001:  ldftn       System.Console.WriteLine
IL_0007:  newobj      System.Action<System.String>..ctor
IL_000C:  stloc.0     
IL_000D:  ldloc.0     
IL_000E:  ldstr       "1"
IL_0013:  callvirt    System.Action<System.String>.Invoke
IL_0018:  ldloc.0     
IL_0019:  ldstr       "2"
IL_001E:  callvirt    System.Action<System.String>.Invoke

ldnull适用于open delegate中的target参数

相关问题