This may be familiar to some. I have an Ex wrapper class that wraps an expression tree with a bunch of implicit conversions and operators. Here is a simplified version
public class Ex { Expression expr; public Ex(Expression expr) { this.expr = expr; } public static implicit operator Expression(Ex rhs) { return rhs.expr; } public static implicit operator Ex(double value) { return new Ex(Expression.Constant(value, typeof(double))); } public static implicit operator Ex(string x) { return new Ex(Expression.Parameter(typeof(double), x)); } public static Ex operator +(Ex left, Ex right) { return new Ex(Expression.Add(left, right)); } public static Ex operator -(Ex rhs) { return new Ex(Expression.Negate(rhs)); } public static Ex operator -(Ex left, Ex right) { return new Ex(Expression.Subtract(left, right)); } public static Ex operator *(Ex left, Ex right) { return new Ex(Expression.Multiply(left, right)); } public static Ex operator /(Ex left, Ex right) { return new Ex(Expression.Divide(left, right)); } }
So here is what I want to do:
{ ... Ex x = "x"; Ex y = 10.0; Ex z = x + y; LambdaExpression lambda = BuildLambda(z); Func<double,double> f = (Func<double,double>)lambda.Compile();
But how do I cross the tree propely and build my lambda (or delegates)
LambdaExpression BuildLambda(Expression e) { ConstantExpression cex = e as ConstantExpression; if(cex != null) { return Expression.Lambda<Func<double>>( cex ); } ParameterExpression pex = e as ParameterExpression; if (pex != null) { Func<Expression, Expression> f = (x) => x; Expression body = f(pex); return Expression.Lambda<Func<double, double>>( body , pex); } BinaryExpression bex = e as BinaryExpression; if (bex != null) { LambdaExpression left = GetLambda(bex.Left); LambdaExpression rght = GetLambda(bex.Right);
I tried several things to convert BinaryExpression bex to lambda, and all were still unavailable. I would like some tips and tricks. Note that the operands of the operation can be other objects of the expression, and only on the leaves of the tree will they be either ParameterExpression or ConstantExpression .
Thanks.
source share