如果我声明一个委托(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/