2013-05-02 6 views
7

Ich habe den folgenden C# -Code.CIL OpCode (Ldarg_0) wird verwendet, obwohl es keine Argumente gibt

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

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

Es produziert die folgende 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 

Nun, was ich nicht verstehe, die Linie bei Offset 0001 ist:

ldarg.0

Ich weiß, was Dieser Opcode ist für, aber ich verstehe nicht wirklich, warum es in th verwendet wird ist Methode, denn es gibt keine Argumente, oder?

Weiß jemand warum? :)

Antwort

19

In Instanzmethoden gibt es ein implizites Argument mit Index 0, das die Instanz darstellt, für die die Methode aufgerufen wird. Es kann mit dem Opcode ldarg.0 auf den IL-Auswertungsstapel geladen werden.

1

Die Linie bei Offset 0001: Lädt das Argument bei Index 0 auf den Auswertestapel.

Weitere: http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldarg_0.aspx

Das Argument bei Index 0 die instance des class die die Methoden HelloWorld und Add, da dies (oder selbst in anderen languajes)

enthält
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) 

... diese letzte Zeile ist als Anruf: this.Add(2,2); in C#.

Verwandte Themen