请看下面的代码:
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();
抛出了一个异常。在方法 Bang
的生成的 CIL 中,我得到了以下内容:
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>
。这是个bug吗?顺便说一下,如果不使用delegate{}
(lambda表达式也一样),代码在语法糖的情况下能够正常工作。
Action good = new Action(base.Foo<string>());
good(); //fine
编辑 我正在使用Windows8 RTM中的VS2012 RTMRel,.net框架4.5。
编辑 此错误现已修复。
[IL]: Error: [ConsoleApplication3.exe : ConsoleApplication3.Derived::<>n__FabricatedMethod1[T]][offset 0x00000001] Unable to resolve token. 1 Error(s) Verifying ConsoleApplication3.exe
- leppie