在运行时更改表达式树

时间:2017-12-16 01:51:53

标签: c#

我是C#表达式树的新手。

我将表达式树传递给下面的方法:

private void MyMethod(System.Linq.Expressions.Expression exp, string param)

我需要能够调整此exp并在运行时根据param值添加两个AND子句。 我该如何做到这一点?

调用此方法的一个示例是:

var temp= MyOtherMethod(cellValue.ExpressionObj, columnName);

感谢。

1 个答案:

答案 0 :(得分:-1)

你应该看看ExpressionVisitor class

如何使用它的好例子可以在Dissecting Linq Expression Trees - Part 2博客文章中找到。

表达式是不可变的,您需要将新表达式返回给调用者以使用更改的表达式。

长话短说:

private Expression MyMethod(Expression<MyClass> exp, string param) {
    if(param == "something") {
        var visitor = new CustomVisitor(); /// You should implement one based on your needs
        return visitor.Visit(exp);
    }
}

编辑:

public class AndAlsoVisitor : ExpressionVisitor {
    protected override Expression VisitLambda<T>(Expression<T> node) {
        // Make it lambda expression
        var lambda = node as LambdaExpression;

        // This should never happen
        if (node != null) {
            // Create property access 
            var lengthAccess = Expression.MakeMemberAccess(
                lambda.Parameters[0],
                lambda.Parameters[0].Type.GetProperty("Length")
            );

            // Create p.Length >= 10
            var cond1 = Expression.LessThanOrEqual(lengthAccess, Expression.Constant(10));
            // Create p.Length >= 3
            var cond2 = Expression.GreaterThanOrEqual(lengthAccess, Expression.Constant(3));
            // Create p.Length >= 10 && p.Length >= 3
            var merged = Expression.AndAlso(cond1, cond2);
            // Merge old expression with new one we have created
            var final = Expression.AndAlso(lambda.Body, merged);
            // Create lambda expression
            var result = Expression.Lambda(final, lambda.Parameters);

            // Return result
            return result;
        }

        return null;
    }
}