【发布时间】:2015-04-25 02:36:50
【问题描述】:
尝试调用带有 ref 参数的示例方法:
public void RefTest(ref int i)
{
Console.WriteLine(i);
i = 18;
}
利用 DLR:
var prog = new Program();
var binder = Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(
CSharpBinderFlags.ResultDiscarded,
"RefTest", null, typeof(Program),
new CSharpArgumentInfo[]{
CSharpArgumentInfo.Create(0,null),
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.IsRef,null)
}
);
ParameterExpression p = Expression.Parameter(typeof(int));
Expression dyn = Expression.Dynamic(binder, typeof(object), Expression.Constant(prog), p);
var lam = Expression.Lambda<Action<int>>(dyn, p).Compile();
lam(9); //RuntimeBinderException
但是,代码失败并出现 RuntimeBinderException,它无法将 int 转换为 ref int。如何解决?
我正在尝试模仿以下代码:
dynamic prog = new Program();
Action<int> lam = i => prog.RefTest(ref i);
lam(9);
我必须使用 DLR 而不是反射,因为提供的对象 (prog) 可能是动态的。
【问题讨论】:
-
虽然 stackoverflow.com/questions/3146317/… 大约是
out而不是ref,但同样的问题适用并且相同的答案解决了,除非我错过了进一步的区别。 -
@Jon 错了。这使用 DLR,而不是反射。如果这是您所期望的答案,那么将参数类型设置为
typeof(int).MakeByRefType()也无济于事。 -
@IllidanS4 另一个示例以与您相同的方式使用表达式树。您是否将 DLR 与表达式的运行时创建混为一谈?
-
@Bas Duh,我 - 你没看到
Expression.Dynamic吗? -
@IllidanS4 只是确保这是有意的