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
?
Expression
is immutable; nothing you can do will change it. The only thing you can do is create a newExpression
based on the change(s) you want and ensure that the relevant variables refer to the newExpression
. – Servy Jan 14 '13 at 19:07