C# Action(arg)和Action.Invoke(arg)之间的差异

C# Action(arg)和Action.Invoke(arg)之间的差异,c#,C#,现在我的问题是 这两种调用操作的方法(如果有的话)有什么区别 一个比另一个好吗 什么时候用哪个 谢谢所有委托类型都有一个编译器生成的Invoke方法。 C#允许您调用委托本身作为调用此方法的快捷方式 它们都编译为相同的IL: C#: Action x=Console.WriteLine; x(“1”); x、 援引(“2”); IL: IL_0000:ldnull IL_0001:ldftn System.Console.WriteLine IL_0007:newobj系统动作 IL_00

现在我的问题是

  • 这两种调用操作的方法(如果有的话)有什么区别

  • 一个比另一个好吗

  • 什么时候用哪个


谢谢

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

它们都编译为相同的IL:

C#:
Action x=Console.WriteLine;
x(“1”);
x、 援引(“2”);
IL:
IL_0000:ldnull
IL_0001:ldftn System.Console.WriteLine
IL_0007:newobj系统动作
IL_000C:stloc.0
IL_000D:ldloc.0
IL_000E:ldstr“1”
IL_0013:callvirt System.Action.Invoke
IL_0018:ldloc.0
IL_0019:ldstr“2”
IL_001E:callvirt System.Action.Invoke

(ldnull
ldnull
用于中的
target
参数)

那么调用哪种方法很重要吗?没有什么区别吗?不,它们都编译到同一个IL。一个是另一个的速记。我能看到的唯一可能的好处是,在使用
invoke
时,您可以检查null并使用较新的c#功能调用它,例如
x?。invoke(“1”)
仅在委托不为null时才会调用它。
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<string> x = Console.WriteLine;
x("1");
x.Invoke("2");
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