我如何定义一个带有out
参数的委托的DynamicMethod,就像这样?
public delegate void TestDelegate(out Action a);
假设我只想调用一个方法,将参数
a
设置为 null
。请注意,我知道处理这个问题的更好方法可能是使方法返回
Action
委托,但这只是一个较大项目中的简化部分,该方法已经返回一个值,我还需要处理 out
参数,因此有了这个问题。我尝试过这样做:
using System;
using System.Text;
using System.Reflection.Emit;
namespace ConsoleApplication8
{
public class Program
{
public delegate void TestDelegate(out Action a);
static void Main(String[] args)
{
var method = new DynamicMethod("TestMethod", typeof(void),
new Type[] { typeof(Action).MakeByRefType() });
var il = method.GetILGenerator();
// a = null;
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Starg, 0);
// return
il.Emit(OpCodes.Ret);
var del = (TestDelegate)method.CreateDelegate(typeof(TestDelegate));
Action a;
del(out a);
}
}
}
然而,我得到了这个:
VerificationException was unhandled:
Operation could destabilize the runtime.
在del(out a);
这一行。
请注意,如果我注释掉加载空值并尝试将其存储到参数中的两行代码,则该方法会在没有异常的情况下运行。
编辑: 这是最好的方法吗?
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Stind_Ref);