我有这段代码生成一个将 myNumber 乘以 5 的委托(delegate)
ParameterExpression numParam = Expression.Parameter(typeof(int), "num");
ConstantExpression five = Expression.Constant(5, typeof(int));
BinaryExpression numMultiply = Expression.Multiply(numParam,five);
让我们创建委托(delegate):
Expression<Func<int, int>> lambda1 =
Expression.Lambda<Func<int, int>>(
numMultiply,
new ParameterExpression[] { numParam });
Console.Write(lambda1.Compile()(4));
现在假设我想将此表达式树更改为 Add
而不是 Multiply
这是新行:
BinaryExpression numAdd = Expression.Add(numParam,five);
但是我怎样才能更改 lambda1 以便它现在将使用 numAdd
而不是 multiply
?
最佳答案
你只需构建一个新的,然后编译它。
Expression<Func<int, int>> lambda1 =
Expression.Lambda<Func<int, int>>(
numAdd,
new ParameterExpression[] { numParam });
来自MSDN page :
Expression trees should be immutable. This means that if you want to modify an expression tree, you must construct a new expression tree by copying the existing one and replacing nodes in it. You can use an expression tree visitor to traverse the existing expression tree.
“应该是”这个短语有点奇怪,但是当您查看 API 时,您会发现所有相关属性(Body、Left、Right)都是只读的。
关于c# - 在运行时更改表达式委托(delegate)主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14324842/