c# - MSIL代码调查

标签 c# .net cil

我现在正在使用 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 并且没有它它会工作吗?

最佳答案

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

如果您在发布/优化模式下编译相同的代码,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 
}

关于c# - MSIL代码调查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12856155/

相关文章:

c# - 将 xml 模式和数据加载到 DataSet(和 datagridview)中

c# - 在 C# 中实现传递身份验证

.net - 在 Mac 上运行的 VM 中开发 C#/.NET 代码有什么陷阱吗?

c# - void 方法在最基本的情况下是否比返回值的方法更快/更少开销?

c# - cecil : Instruction. Instruction.OpCode.Code值对应的操作数类型

.NET 错误 : ldtoken of an instantiated generic method

c# - MVC模型是Poco类,结构有数据还是业务层?

c# - 如何用另一个表/列表中的匹配值替换 id?

c# - TFS API - 如何从特定团队项目中获取工作项

.net - 从旧版 (v3.0) Facebook .Net SDK 迁移到最新版 (v5.0)