请看下面的代码:
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/