为什么C#编译器在IL中发出额外的OpCode?

前端之家收集整理的这篇文章主要介绍了为什么C#编译器在IL中发出额外的OpCode?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我有一个Multiply方法定义为:
  1. public static class Experiment
  2. {
  3. public static int Multiply(int a,int b)
  4. {
  5. return a * b;
  6. }
  7. }

那么为什么编译器会发出这个IL:

  1. .method public hidebysig static int32 Multiply(int32 a,int32 b) cil managed
  2. {
  3. .maxstack 2 //why is it not 16?
  4. .locals init (
  5. [0] int32 CS$1$0000) //what is this?
  6. L_0000: nop //why this?
  7. L_0001: ldarg.0
  8. L_0002: ldarg.1
  9. L_0003: mul
  10. L_0004: stloc.0 //why this?
  11. L_0005: br.s L_0007 //why this?
  12. L_0007: ldloc.0 //why this?
  13. L_0008: ret
  14. }

正如你所看到的,它还包含一些对我没有意义的额外操作码,实际上我期望以下IL:

  1. .method public hidebysig static int32 MyMethod(int32 a,int32 b) cil managed
  2. {
  3. .maxstack 16
  4. L_0000: ldarg.0
  5. L_0001: ldarg.1
  6. L_0002: mul
  7. L_0003: ret
  8. }

这是完全相同的事情.

所以问题是,为什么编译器会在IL中发出额外的OpCode?

我正在使用调试模式.

解决方法

主要用于调试和断点支持;在这里看到答案: Why are these nop instructions in my debug build?

猜你在找的C#相关文章