我最近一直在研究 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# 编译器不必担心优化?