最近我在深入研究IL,发现C#编译器有一些奇怪的行为。以下方法是一个非常简单且可验证的应用程序,它将立即以退出代码1退出:
static int Main(string[] args)
{
return 1;
}
当我使用Visual Studio Community 2015编译此代码时,会生成以下的IL代码(已添加注释):
.method private hidebysig static int32 Main(string[] args) cil managed
{
.entrypoint
.maxstack 1
.locals init ([0] int32 V_0) // Local variable init
IL_0000: nop // Do nothing
IL_0001: ldc.i4.1 // Push '1' to stack
IL_0002: stloc.0 // Pop stack to local variable 0
IL_0003: br.s IL_0005 // Jump to next instruction
IL_0005: ldloc.0 // Load local variable 0 onto stack
IL_0006: ret // Return
}
如果我要手写这个方法,似乎可以通过以下的IL实现相同的结果:.method static int32 Main()
{
.entrypoint
ldc.i4.1 // Push '1' to stack
ret // Return
}
这种行为是否有我不知道的潜在原因?
还是只是已组装的IL对象代码在后续进行了进一步优化,因此C#编译器不需要担心优化问题?