gpt4 book ai didi

c# - 委托(delegate)的编译器处理

转载 作者:行者123 更新时间:2023-11-30 22:48:21 25 4
gpt4 key购买 nike

如果我声明一个委托(delegate)

public delegate void firstDelegate(string str);

firstDelegate handler = Strfunc;

handler("Hello World");

..
static void Strfunc(string str)
{
Console.WriteLine(str);
}

编译器会翻译下面这行吗

firstDelegate handler=Strfunc;

进入

firstDelegate=new firstDelegate(Strfunc);

最佳答案

没错。这是反射器的拆卸:

.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 3
.locals init (
[0] class ConsoleApplication4.Program/firstDelegate handler)
L_0000: nop
L_0001: ldnull
L_0002: ldftn void ConsoleApplication4.Program::Strfunc(string)
L_0008: newobj instance void ConsoleApplication4.Program/firstDelegate::.ctor(object, native int)
L_000d: stloc.0
L_000e: ldloc.0
L_000f: ldstr "Hello World"
L_0014: callvirt instance void ConsoleApplication4.Program/firstDelegate::Invoke(string)
L_0019: nop
L_001a: ret
}

在 C# 中看起来像这样:

private static void Main(string[] args)
{
firstDelegate handler = new firstDelegate(Program.Strfunc);
handler("Hello World");
}

关于c# - 委托(delegate)的编译器处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1746016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com