【问题标题】:Investigation of MSIL codeMSIL代码调查
【发布时间】:2012-10-12 17:53:18
【问题描述】:

我现在正在使用 IL 代码,将来需要自己编写。由于误解,我有些担心。这是C#中的一个简单方法

public static string Method1(int id)
 {
   return Method2(id);
 }

这是它的 IL 代码

.method public hidebysig static string 
          Method1(int32 id) cil managed
  {
    // 
    .maxstack  1
    .locals init ([0] string CS$1$0000)
    IL_0000:  nop          // Why?
    IL_0001:  ldarg.0
    IL_0002:  call       string MyNamespace.MyClass::Method2(int32)
    IL_0007:  stloc.0    // storing a return value of MyClass::Method2 to local variable.
    IL_0008:  br.s       IL_000a   // Why?

    IL_000a:  ldloc.0    // Does it really require and why?
    IL_000b:  ret
  } // end of method MyClass::Method1
由于某种原因,CIL 中的

每个 方法都有nop 操作。为什么会有它? 在我的情况下,是否有必要使用br.s IL_000a,没有它是否可以工作?

【问题讨论】:

  • “自己写”,你会写IL吗?
  • 我已经发布了 IL 应该作为对同行答案的编辑

标签: c# .net cil


【解决方案1】:

nops 允许您调试(设置断点),如果您在发布模式下编译,您将在代码中看到更少的 nops。

如果您在发布/优化模式下编译相同的代码,IL 应该看起来更清晰:

.method public hidebysig static string Method1(int32 id) cil managed
{
    .maxstack 8
    L_0000: ldarg.0 
    L_0001: call string MyNamespace.MyClass::Method2(int32)
    L_0006: ret 
}

【讨论】:

  • 我编辑了它在发布版本中的样子——希望你不介意。您涵盖了关键点,因此第二个答案似乎是多余的。
  • 马克,谢谢,现在更清楚了。但是为什么 .maxstack 等于 8?
  • 还有一件事:我不必使用 L_00XX: 指令,对吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
  • 1970-01-01
  • 1970-01-01
  • 2010-11-26
  • 1970-01-01
  • 2011-05-01
  • 1970-01-01
相关资源
最近更新 更多