我遇到了一个有趣的问题,请看下面的代码。
class Program
{
static void Main(string[] args)
{
var testDelegate = (System.Delegate)(Action)(() =>
{
Console.WriteLine("Hey!");
});
}
}
这按预期工作(什么都不做,因为我们没有调用任何东西),但现在用“new Action”替换“(Action)”,看看会发生什么:
class Program
{
static void Main(string[] args)
{
var testDelegate = (System.Delegate)new Action(() =>
{
Console.WriteLine("Hey!");
});
}
}
它编译得很好,但是当我尝试运行它时,我得到一个“InvalidProgramException”。关于为什么会发生这种情况有什么想法吗?
编辑
这是 DEBUG 构建,发布构建没有显示相同的问题。
主要的 IL:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 3 (0x3)
.maxstack 0
.locals init ([0] class [mscorlib]System.Delegate testDelegate)
IL_0000: nop
IL_0001: stloc.0
IL_0002: ret
} // end of method Program::Main
委托(delegate)的 IL:
.method private hidebysig static void '<Main>b__0'() cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
// Code size 13 (0xd)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "Hey!"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
} // end of method Program::'<Main>b__0'
最佳答案
如果为 Main 生成的 IL 是准确的,那么看起来像是 C# 编译器错误。 Main 中 IL_0001 处的指令从计算堆栈弹出一些不存在的东西。 JIT 编译器注意到这一点,并在对 Main 进行 JIT 编译时引发 InvalidProgramException。
编辑:我猜这是您遇到的编译器错误:http://connect.microsoft.com/VisualStudio/feedback/details/371711/invalidprogramexception-c-compiler-3-5
关于c# - 委托(delegate)类型转换的乐趣 -> InvalidProgramException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5243065/