我正在尝试弄清楚如何创建调用具有引用参数的方法的表达式。
让我用一个简单(但人为)的例子来解释我的问题。考虑方法:
public static int TwiceTheInput(int x)
{
return x*2;
}
我可以创建一个表达式来调用上面的方法,方法如下:
{
var inputVar = Expression.Variable(typeof (int), "input");
var blockExp =
Expression.Block(
new[] {inputVar}
, Expression.Assign(inputVar, Expression.Constant(10))
, Expression.Assign(inputVar, Expression.Call(GetType().GetMethod("TwiceTheInput", new[] { typeof(int) }), inputVar))
, inputVar
);
var result = Expression.Lambda<Func<int>>(blockExp).Compile()();
}
在执行时,上面的“结果”应该以 20 的值结束。 现在考虑使用引用参数的 TwiceTheInput() 版本:
public static void TwiceTheInputByRef(ref int x)
{
x = x * 2;
}
如何编写类似的表达式树来调用 TwiceTheInputByRef() 并通过引用传递参数?
解决方案:(感谢 Cicada)。使用:
Type.MakeByRefType()
这是生成表达式树的代码段:
{
var inputVar = Expression.Variable(typeof(int), "input");
var blockExp =
Expression.Block(
new[] { inputVar }
, Expression.Assign(inputVar, Expression.Constant(10))
, Expression.Call(GetType().GetMethod("TwiceTheInputByRef", new[] { typeof(int).MakeByRefType() }), inputVar)
, inputVar
);
var result = Expression.Lambda<Func<int>>(blockExp).Compile()();
}
最佳答案
你不需要做太多改变,只需删除 Assign
并将 typeof(int)
更改为 typeof(int).MakeByRefType()
.
var blockExp = Expression.Block(
new[] { inputVar }
, Expression.Assign(inputVar, Expression.Constant(10))
, Expression.Call(
typeof(Program).GetMethod(
"TwiceTheInputByRef", new [] { typeof(int).MakeByRefType() }),
inputVar)
, inputVar
);
关于c# - 如何使用表达式树调用带有引用变量的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14940171/