小编lpm*_*ell的帖子

为什么这个非常简单的C#方法会产生这种不合逻辑的CIL代码?

我最近一直在挖掘IL,我注意到了C#编译器的一些奇怪的行为.以下方法是一个非常简单且可验证的应用程序,它将立即退出,退出代码为1:

static int Main(string[] args)
{
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

当我使用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
}
Run Code Online (Sandbox Code Playgroud)

如果我要手写这个方法,看起来使用以下IL可以获得相同的结果:

.method …
Run Code Online (Sandbox Code Playgroud)

.net c# cil ildasm ilasm

16
推荐指数
2
解决办法
795
查看次数

标签 统计

.net ×1

c# ×1

cil ×1

ilasm ×1

ildasm ×1