c# - 编译器为匿名方法生成了不正确的代码 [MS BUG FIXED]

标签 c# .net delegates cil anonymous-methods

请看下面的代码:

public abstract class Base
{
    public virtual void Foo<T>() where T : class
    {
        Console.WriteLine("base");
    }
}

public class Derived : Base
{
    public override void Foo<T>()
    {
        Console.WriteLine("derived");
    }

    public void Bang()
    {
        Action bang = new Action(delegate { base.Foo<string>(); });
        bang();    //VerificationException is thrown
    }
}

new Derived().Bang();抛出异常。在方法生成的 CIL 中 Bang我得到了:

call instance void ConsoleApp.Derived::'<>n__FabricatedMethod1'<string>()

以及编译器生成方法的签名:

method private hidebysig 
    instance void '<>n__FabricatedMethod1'<T> () cil managed 
{
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
        01 00 00 00
    )       
    .maxstack 8

    IL_0000: ldarg.0
    IL_0001: call instance void ConsoleApp.Base::Foo<!!T>()
    IL_0006: ret
}

我认为正确的代码应该是'<>n__FabricatedMethod1'<class T> .这是一个错误吗? 顺便说一下,不使用 delegate{ } (lambda 表达式相同),代码可以很好地使用语法糖。

Action good = new Action(base.Foo<string>());
good();  //fine

编辑 我在 windows8 RTM、.net framework 4.5 中使用 VS2012 RTMRel

编辑此错误现已修复。

最佳答案

它被确认为一个错误并且now fixed

更新:Connect 文章不再存在。该错误已修复。

关于c# - 编译器为匿名方法生成了不正确的代码 [MS BUG FIXED],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13071923/

相关文章:

ios - 委托(delegate)是否仍然不安全未保留?

c# - 货币类型的算术溢出错误

c# - 加速更新 SQL 查询

c# - 'MSDAORA.1' 提供者未在本地机器上注册

c# - 从 Windows 服务调用时,Process.Start 不起作用

c# - 为什么 .net 委托(delegate)赋值运算符没有将引用分配给原始委托(delegate)?

c# - LINQ 中的日期差异逻辑

c# - IComparable 的接口(interface)约束

c# - Java 方法中允许递归调用吗?

c# - 转换为 void 返回委托(delegate)的匿名函数无法返回值