Expression.Lambda指定子类型的ParameterExpression

时间:2018-03-01 12:18:21

标签: c# linq expression-trees

我想加入OrElse的一些表达式,这个:

Expression<Func<Customer, bool>> extraWhere = x => x.ExtraFields.Any(a => a.Value.Contains(filterText));

使用此代码:

var buildWhereColumns = BuildWhereColumns<Customer>(columns, filterText);
var combined = Expression.OrElse(buildWhereColumns.Body, extraWhere.Body);
var paramX = Expression.Parameter(typeof(Customer), "x");
var replacerX = new ParameterReplacer(paramX);
var newcombined = replacerX.Visit(combined);

var lambda = Expression.Lambda<Func<Customer, bool>>(newcombined, paramX);

我在replacerX.Visit上得到了一个ArgumentException,因为它在Any中看到了'a'作为客户。如何指定?(/ p>)的(ParameterExpression?)类型

ParameterReplacer:

class ParameterReplacer : ExpressionVisitor
{
    private readonly ParameterExpression parameter;

    internal ParameterReplacer(ParameterExpression parameter)
    {
        this.parameter = parameter;
    }

    protected override Expression VisitParameter
        (ParameterExpression node)
    {
        return parameter;
    }
}

1 个答案:

答案 0 :(得分:0)

感谢Titian Cernicova-Dragomir的评论,我通过修复ParameterReplacer解决了这个问题。我添加了一个额外的ParameterExpression:

var paramX = Expression.Parameter(typeof(Customer), "x");
var paramA = Expression.Parameter(typeof(ExtraFields), "a");
var replacerX = new ParameterReplacer(paramX, paramA);
var newcombined = replacerX.Visit(combined);

和ParameterReplacer

class ParameterReplacer : ExpressionVisitor
{
    private readonly ParameterExpression[] parameter;

    internal ParameterReplacer(params ParameterExpression[] parameter)
    {
        this.parameter = parameter;
    }

    protected override Expression VisitParameter
        (ParameterExpression node)
    {
        return parameter.Single(x => x.Type == node.Type);
    }
}