Delegate.Invoke 和 Delegate()的区别
kelvin 发布于 2021-04-09

例如下面的代码

static async Task Main(string[] args)
{
   DelegateDemo delegate = new DelegateDemo(CallMe);
   delegate.Invoke("helloworld");
   delegate("helloworld");
}

public delegate void DelegateDemo(string message);
public static void Call(string message)
{

}

对应的IL代码如下

IL_001a: ldarg.0
IL_001b: ldfld class ConsoleApplication1.Program/DelegateDemo ConsoleApplication1.Program/'<Main>d__1'::'<mydelegate>5__1'
IL_0020: ldstr "helloworld"
IL_0025: callvirt instance void ConsoleApplication1.Program/DelegateDemo::Invoke(string)
IL_002a: nop
IL_002b: ldarg.0
IL_002c: ldfld class ConsoleApplication1.Program/DelegateDemo ConsoleApplication1.Program/'<Main>d__1'::'<mydelegate>5__1'
IL_0031: ldstr "helloworld"
IL_0036: callvirt instance void ConsoleApplication1.Program/DelegateDemo::Invoke(string)
IL_003b: nop

看起来没有区别,不过使用Invoke有个好处,可以进行Null检测

DelegateDemo mydelegate = null;
mydelegate?.Invoke("helloworld");
mydelegate("helloworld"); // 会抛出System.NullReferenceException
kelvin
关注 私信
文章
92
关注
0
粉丝
0