.net - 如何在 CLR 上学习 IL

标签 .net clr il

由于这些 IL 代码我看到的更多,我喜欢学习如何正确解释它们。

我找不到像 C# Compiler 或任何其他文档这样的文档,所以我想在我学习了这些常见的之后,我几乎可以处理其余的事情:

以下是一些示例 IL 代码,其中包含我需要了解的内容:

示例 1:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       15 (0xf)
  .maxstack  1
  .locals init ([0] class EnumReflection.DerivedClass derivedClass)
  IL_0000:  nop
  IL_0001:  newobj     instance void EnumReflection.DerivedClass::.ctor()
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  callvirt   instance void EnumReflection.DerivedClass::WriteOutput()
  IL_000d:  nop
  IL_000e:  ret
} // end of method Program::Main

样本 2:
.method public hidebysig specialname rtspecialname 
        instance void  .ctor() cil managed
{
  // Code size       38 (0x26)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldstr      "Hello"
  IL_0006:  stfld      string EnumReflection.DerivedClass::hello
  IL_000b:  ldarg.0
  IL_000c:  ldstr      "World"
  IL_0011:  stfld      string EnumReflection.DerivedClass::world
  IL_0016:  ldarg.0
  IL_0017:  ldc.i4.s   123
  IL_0019:  stfld      int32 EnumReflection.DerivedClass::age
  IL_001e:  ldarg.0
  IL_001f:  call       instance void EnumReflection.BaseClass::.ctor()
  IL_0024:  nop
  IL_0025:  ret
} // end of method DerivedClass::.ctor

我知道这些代码是做什么的,因为我制作了它们 :-) 但是我想了解更多有关相应 IL 代码的信息。

这些样本包含 IL 代码,如 你能用问号解释命令吗?还有那些命令代表什么?所以我们可以很容易地记住它们。
  • nop(用于调试 - 无操作)
  • newobj(似乎是在堆中创建新对象)
  • STLoc.0 ?
  • ldloc.0 ?
  • 退?
  • ldarg.0 ?
  • ldstr ?
  • stfld ?
  • ldc.i4.s ?
  • .ctor - 构造函数

  • 理解 IL 很重要,因为它揭示了特定编译器如何生成代码并在特定情况下采取行动。

    但是,我找不到一个很好的文档,其中包含有关 IL 的示例。 CLR with C# 3.0 是一本好书,但最终它不是一本 IL 书,因此它没有解释有关 IL 的所有内容。

    编辑:

    我找到了规范,他们告诉了这些:感谢@usr。
  • nop(用于调试 - 无操作)
  • newobj - 创建一个新对象
  • STLoc.0 - 从堆栈弹出值到局部变量
  • ldloc.0 ? - 将局部变量加载到堆栈
  • ret - 从方法返回
  • ldarg.0 - 将参数 0 加载到堆栈中。
  • ldstr - 加载文字字符串
  • stfld - 存储到对象的字段中
  • ldc.i4.s - 将 num 作为 int32 短格式插入堆栈。
  • .ctor - 构造函数
  • 最佳答案

    Microsoft standardized the CLR and published those standards . Part III包含了丰富的IL/CIL信息,适合学习。这是一份优秀的文件。

    您还可以通过示例学习 IL。在 C# 中编译一些简单的方法并查看反射器中的 IL(它有一个 IL 模式)。

    关于.net - 如何在 CLR 上学习 IL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10260272/

    相关文章:

    c# - 如何在 IIS 上正确开发和部署现有 asp.net 应用程序的功能

    .net - CLR token 可以为零或负数

    c# - Marshal.GetFunctionPointerForDelegate 如何作用于实例成员?

    .net - MSIL 引用文献

    c# - 如何从 .NET 程序集中读取数组初始值设定项

    c# - 再添加一个int变量时生成的不同IL

    .net - 使用 foreach/WhenAll 时实际上会发生什么?

    .net - 重新执行错误:退出状态1:输出:ProcessUtilityVMImage\UtilityVM:系统找不到指定的路径

    c# - 如何从列表<string>中找到元素的索引,元素包含特定部分

    c# - Expression.Coalesce 的转换参数是做什么用的?