代码:
public int Add(int a, int b) { int c = 100; return ((a + b) + c); } 查看IL: .method public hidebysig instance int32 Add(int32 a, int32 b) cil managed { .maxstack 2 .locals init ( [0] int32 c, [1] int32 CS$1$0000) L_0000: nop L_0001: ldc.i4.s 100 L_0003: stloc.0 L_0004: ldarg.1 L_0005: ldarg.2 L_0006: add L_0007: ldloc.0 L_0008: add L_0009: stloc.1 L_000a: br.s L_000c L_000c: ldloc.1 L_000d: ret } emit: var addMethod=tb.DefineMethod("Add", MethodAttributes.Public, CallingConventions.Standard, typeof(int), new Type[] { typeof(int), typeof(int) }); addMethod.DefineParameter(1,ParameterAttributes.None,"a"); addMethod.DefineParameter(2, ParameterAttributes.None, "b"); var il2=addMethod.GetILGenerator(); var lb=il2.DeclareLocal(typeof(int)); lb.SetLocalSymInfo("c"); il2.Emit(OpCodes.Ldc_I4, 100); il2.Emit(OpCodes.Stloc, 0); il2.Emit(OpCodes.Ldarg_1); il2.Emit(OpCodes.Ldarg_2); il2.Emit(OpCodes.Add); il2.Emit(OpCodes.Ldloc_0); il2.Emit(OpCodes.Add); il2.Emit(OpCodes.Ret); 查看: IL: .method public instance int32 Add(int32 a, int32 b) cil managed { .maxstack 2 .locals init ( [0] int32 num) L_0000: ldc.i4 100 L_0005: stloc num L_0009: nop L_000a: nop L_000b: ldarg.1 L_000c: ldarg.2 L_000d: add L_000e: ldloc.0 L_000f: add L_0010: ret } 代码: public int Add(int a, int b) { int num = 100; return ((a + b) + num); } 是否说明编译器还不够聪明呢?没自己写的IL简单。另外明明声明的局部变量是c,如何变成num了?