Reputation: 1213
I'm playing around with Expression trees in C# and would like to modify an expression.
I used this example however in the example they reuse the left and right node. How would I go about modifying either of the nodes?
I got the following code:
[TestMethod]
public void ExpressionDemo_ModifiesExpression()
{
var demo = new ExpressionDemo();
var expression = demo.ModifyAddition((Expression<Func<int, int>>)(x => x + 1));
}
I call ModifyAddition using a simple + 1 addition Func. I would like to modify the right operand (1) to a different integer.
public class ExpressionDemo : ExpressionVisitor
{
public Expression<Func<int, int>> ModifyAddition(Expression func)
{
return (Expression<Func<int, int>>) Visit(func);
}
protected override Expression VisitBinary(BinaryExpression node)
{
if (node.NodeType == ExpressionType.Add)
{
Expression left = node.Left;
Expression right = ???
return Expression.MakeBinary(ExpressionType.Add, left, right);
}
return base.VisitBinary(node);
}
}
I'm confused as how to construct the proper right operand so I can return a new BinaryExpression.
Upvotes: 0
Views: 692
Reputation: 1504122
Do you just want to turn any x + y
into x + 1
? If so, I suspect you just want:
Expression right = Expression.Constant(1);
(You should validate that the addition type is for integers, of course.)
If that's not what you're trying to do, please be more specific.
Upvotes: 4