Action(arg)和Action. invoke (arg)的区别
本文关键字:Action arg 区别 invoke | 更新日期: 2023-09-27 18:12:24
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的两种方式有什么区别?
一个比另一个好吗?
何时使用哪个?
谢谢
所有委托类型都有编译器生成的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
表示开放委托中的target
参数)