由于我更多地看到这些IL代码,我希望学习如何正确解释它们。
我找不到像C#编译器或其他任何文档,所以我认为在学习这些常见的代码之后,我就可以照顾好其余的部分:
以下是一些示例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 ?
- ret ?
- ldarg.0 ?
- ldstr ?
- stfld ?
- ldc.i4.s ?
- .ctor - 构造函数
理解IL很重要,因为它揭示了特定编译器如何生成代码并在特定情况下执行的方式。
但是,我找不到一个很好的文档,其中包含有关IL的示例。CLR与C#3.0是一本不错的书,但最终它不是一本IL书,因此它并没有解释关于IL的所有内容。
编辑:
我已经找到了规范,它们说明了以下内容:感谢@usr。
- nop(调试用-无操作)
- newobj - 创建新对象
- stloc.0 - 从堆栈弹出值到本地变量
- ldloc.0 ? - 将本地变量加载到堆栈上
- ret - 从方法返回
- ldarg.0 - 加载参数0到堆栈上。
- ldstr - 加载文字字符串
- stfld - 存储在对象的字段中
- ldc.i4.s - 将数字作为int32推送到堆栈上,短格式。
- .ctor - 构造函数