如何为具有out-parameter的委托定义一个-parameter,如下所示?
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);线路上。
请注意,如果我注释掉在堆栈上加载null并试图将其存储到参数中的两行,则该方法将无异常地运行。
编辑:这是最好的方法吗?
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Stind_Ref);发布于 2009-08-18 09:46:37
out参数只是一个ref参数,其中OutAttribute应用于该参数。
要存储到by参数,需要使用stind操作码,因为参数本身是指向对象实际位置的托管指针。
ldarg.0
ldnull
stind.refhttps://stackoverflow.com/questions/1292693
复制相似问题