Skip to main content
 首页 » 编程设计

c#之在 IL 生成中将局部变量加载到堆栈以进行方法调用

2024年02月23日16mayingbao

我正在尝试生成 IL 以模仿以下方法 MyMethod:

public void DoSomething(object a, object b, string c, string d){...}; 
public virtual void MyMethod(object a, object b)  
{ 
    DoSomething(a, b, "hello", this.SomeInstanceString); 
} 

这是我目前所知道的,但我无法理解将第 3 个和第 4 个参数加载到堆栈以调用 DoSomething(a, b, "hello", this. SomeInstanceString)):

 MethodBuilder myMethod = typeBuilder.DefineMethod("MyMethod", 
    MethodAttributes.Public | MethodAttributes.Virtual, typeof(void), new[]  
       { typeof(object), typeof(object) }); 
 ILGenerator myMethodILGen = mbFromCustomObject.GetILGenerator(); 
 myMethodILGen.Emit(OpCodes.Ldarg_0); 
 myMethodILGen.Emit(OpCodes.Ldarg_1); 
 // How do I load the string "hello" and the local instance  
 // variable this.SomeInstanceString onto the stack? 
 myMethodILGen.Emit(OpCodes.Call, GetMethodInfoForDoSomething()); 
 myMethodILGen.Emit(OpCodes.Ret); 

那么,如何将字符串"hello" 和局部实例变量this.SomeInstanceString 加载到堆栈上以调用DoSomething?

请您参考如下方法:

加载字符串文字相当容易。

myMethodILGen.Emit(OpCodes.Ldstr, "hello"); 

从对象实例中加载字段要求您首先将对象实例加载到堆栈上,然后使用 Ldfld 操作码。您应该已经为您的 SomeInstanceString 字段准备了一个 FieldBuilder,您可以将其用于此目的。

FieldBuilder fieldBuilder = typeBuilder.DefineField( 
                    "SomeInstanceString", 
                    typeof(string), 
                    FieldAttributes.Public); 
 
myMethodILGen.Emit(OpCodes.Ldarg_0); 
myMethodILGen.Emit(OpCodes.Ldfld, fieldBuilder); 

另外,请记住,Ldarg_0 并不像您认为的那样。实例方法有一个隐式参数,它位于零槽中,其中包含该方法当前在其​​中运行的实例。这就是我们使用 Ldarg_0 取消引用该字段的原因,因为您可能需要该方法所在的实例。但这不适用于静态方法。