Reputation: 148534
I have this code which produce a delegate which multiply myNumber by 5
ParameterExpression numParam = Expression.Parameter(typeof(int), "num");
ConstantExpression five = Expression.Constant(5, typeof(int));
BinaryExpression numMultiply = Expression.Multiply(numParam,five);
Lets create the delegate :
Expression<Func<int, int>> lambda1 =
Expression.Lambda<Func<int, int>>(
numMultiply,
new ParameterExpression[] { numParam });
Console.Write(lambda1.Compile()(4));
now let's say I want to change this expression tree to Add
instead of Multiply
here is the new line :
BinaryExpression numAdd = Expression.Add(numParam,five);
But how can I change the lambda1 so that it will now will use numAdd
instead of multiply
?
Upvotes: 2
Views: 1580
Reputation: 273274
You just build a new one, and compile it.
Expression<Func<int, int>> lambda1 =
Expression.Lambda<Func<int, int>>(
numAdd,
new ParameterExpression[] { numParam });
From the 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.
The "should be" phrase is a little odd but when you look at the API you will see that all relevant properties (Body, Left, Right) are read-only.
Upvotes: 6