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

标签 c# delegates

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

相关文章:

c# - 如何检查一个对象的多个属性是否具有相同的条件?

c# - NLog:如何控制 LogEventInfo 对象的消息格式?

ios - 如何从 Storyboard 设置 Split View Controller Delegate?

c# - 线程构造函数中显式委托(delegate)和方法组的区别

c# - 在 .NET 中使用返回值执行多线程或异步任务的最佳方法是什么?

C# 和委托(delegate)

c# - Microsoft Bot Framework,缺少子类型

c# - Entity Framework 一对多 TPH 映射

C# 容器 - 矢量,。列表、队列、堆栈等

ios - CAAnimationGroup 中的 CAAnimation 委托(delegate)