我刚开始看IL一点,我很好奇,如果我尝试(如下图所示),从编译器的输出有任何意外的副作用去除多余的代码。
一对夫妇对结果quesiton的:
- 什么是在原NOP操作的目的是什么?
- 什么是br.s在在原来的方法到底目的何在?
- 是重新编写的版本不正当以任何方式?
原来C#代码:
class Program {
public static int Main() {
return Add(1, 2);
}
public static int Add(int a, int b) {
return a + b;
}
}
编译csc.exe
与拆卸它ildasm.exe
(原文):
.method public hidebysig static int32 Main() cil managed
{
.entrypoint
.maxstack 2
.locals init (int32 V_0)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: call int32 Program::Add(int32, int32)
IL_0008: stloc.0
IL_0009: br.s IL_000b
IL_000b: ldloc.0
IL_000c: ret
}
.method public hidebysig static int32 Add(int32 a,
int32 b) cil managed
{
.maxstack 2
.locals init (int32 V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: add
IL_0004: stloc.0
IL_0005: br.s IL_0007
IL_0007: ldloc.0
IL_0008: ret
}
重新写入(产生相同的输出):
.method public hidebysig static int32 Main() cil managed
{
.entrypoint
.maxstack 2
ldc.i4.1
ldc.i4.2
call int32 Program::Add(int32, int32)
ret
}
.method public hidebysig static int32 Add(int32 a, int32 b) cil managed
{
.maxstack 2
ldarg.0
ldarg.1
add
ret
}