11

我有以下 C# 代码。

public void HelloWorld()
{
    Add(2, 2);
}

public void Add(int a, int b)
{
    //Do something
}

它产生以下 CIL

.method public hidebysig instance void  HelloWorld() cil managed
{
  // Code size       11 (0xb)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  ldc.i4.2
  IL_0003:  ldc.i4.2
  IL_0004:  call       instance void ConsoleApplication3.Program::Add(int32,
                                                                      int32)
  IL_0009:  nop
  IL_000a:  ret
} // end of method Program::HelloWorld

现在,我不明白的是偏移量 0001 处的行:

ldarg.0

我知道那个操作码是做什么用的,但我真的不明白为什么在这个方法中使用它,因为没有参数,对吧?

有人知道为什么吗?:)

4

3 回答 3

22

在实例方法中,有一个索引为 0 的隐式参数,表示调用该方法的实例。它可以使用ldarg.0操作码加载到 IL 评估堆栈上。

于 2013-05-02T19:53:05.860 回答
16

我认为ldarg.0正在加载this到堆栈上。查看此答案 MSIL 问题(基本)

于 2013-05-02T19:31:40.517 回答
2

偏移量 0001 处的行:将索引 0 处的参数加载到评估堆栈上。

查看更多:http: //msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldarg_0.aspx

索引 0 处的参数是instance包含class方法的 theHelloWorldAdd, as this (或其他语言中的 self )

 IL_0001:  ldarg.0   //Loads the argument at index 0 onto the evaluation stack.

 IL_0002:  ldc.i4.2  //Pushes a value 2 of type int32 onto the evaluation stack.

 IL_0003:  ldc.i4.2  //Pushes a value 2 of type int32 onto the evaluation stack.

 IL_0004:  call instance void ConsoleApplication3.Program::Add(int32, int32)

...最后一行是调用:this.Add(2,2);在 C# 中。

于 2013-05-22T15:56:10.313 回答