开发者

Fun with delegate casting -> InvalidProgramException

开发者 https://www.devze.com 2023-02-15 21:34 出处:网络
I\'ve encountered an interesting problem, see the following code. class Program { static void Main(string[] args)

I've encountered an interesting problem, see the following code.

class Program
{
    static void Main(string[] args)
    {        
        var testDelegate = (System.Delegate)(Action)(() =>
        {
            Console.WriteLine("Hey!");
        });
    }
}

This works as expected (does nothing, as we don't invoke anything), but now replace the "(Action)" with "new Action" and see what happens:

class Program
{
    static void Main(string[] args)
    {
        var testDelegate = (System.Delegate)new Action(() =>
        {
            Console.WriteLine("Hey!");
        });
    }
}

It compiles just fine, but when I try to run it I get an "InvalidProgramException". Any thoughts on why this happens?

EDIT

开发者_开发技巧

This is the DEBUG build, the release build didn't show the same problem.

IL for Main:

.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

IL for the delegate:

.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'


Looks like a C# compiler bug if that generated IL for Main is accurate. The instruction at IL_0001 in Main pops something off the evaluation stack that isn't there. The JIT compiler notices this and raises InvalidProgramException when Main is being JIT compiled.

Edit: My guess is that this is the compiler bug you're running into: http://connect.microsoft.com/VisualStudio/feedback/details/371711/invalidprogramexception-c-compiler-3-5

0

精彩评论

暂无评论...
验证码 换一张
取 消