【问题标题】:C# delegate instantiation syntax [duplicate]C#委托实例化语法[重复]
【发布时间】:2014-09-04 23:46:43
【问题描述】:

我见过实例化委托对象的不同形式。例如:

我有以下委托和方法。

public delegate void Delegate();
public void foo();

以及这两个用于实例化的选项。

Delegate del = new Delegate(foo);
Delegate del = foo;

我的问题如下:这两个语句在语义上有什么区别?

【问题讨论】:

    标签: c# delegates instantiation


    【解决方案1】:

    简短的回答是没有。

    长答案是,它们都编译为相同的 IL。

    Delegate del1 = foo;
    Delegate del2 = new Delegate(foo);
    

    编译成

    IL_0001:  ldarg.0     
    IL_0002:  ldftn       UserQuery.foo
    IL_0008:  newobj      UserQuery+Delegate..ctor
    IL_000D:  stloc.0     // del1
    IL_000E:  ldarg.0     
    IL_000F:  ldftn       UserQuery.foo
    IL_0015:  newobj      UserQuery+Delegate..ctor
    IL_001A:  stloc.1     // del2
    

    【讨论】:

    • @RihardMarius 有很多工具。您可以指示 C# 编译器将其转储 - 或获取 ILSpy、Dotpeek、Reflector 等工具。
    • @RihardMarius 我用过 LinqPad。这是一个用于快速原型设计和运行 C# 代码 sn-ps 的绝佳工具。
    【解决方案2】:

    绝对没有。编译器会将第二个转换为Delegate 的实例化,就像第一个一样:

    // Delegate del = new Delegate(foo);
    ldftn    void App.Program::foo()
    newobj   instance void App.Program/Delegate::.ctor(object, native int)
    stloc.0
    
    // Delegate de2l = foo;
    ldftn    void App.Program::foo()
    newobj   instance void App.Program/Delegate::.ctor(object, native int)
    stloc.1
    

    【讨论】:

      【解决方案3】:

      据我所知没有。编译器将为您生成新的。 一个类似的问题是answered here。这种快捷方式是从 C# 2.0 开始引入的 - MSDN

      【讨论】:

      • 感谢您提供的链接,我发誓我进行了搜索,但没有找到任何与我的问题相近的内容。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 2022-07-22
      • 1970-01-01
      • 2013-06-10
      相关资源
      最近更新 更多