[英]Expression.Lambda specify ParameterExpression of sub type
I want to join some expressions with OrElse, this one: 我想与OrElse一起加入一些表达式:
Expression<Func<Customer, bool>> extraWhere = x => x.ExtraFields.Any(a => a.Value.Contains(filterText));
with this code: 使用此代码:
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);
I get an ArgumentException on the replacerX.Visit because it sees the 'a' in the Any as a Customer. 我在replacerX.Visit上收到ArgumentException,因为它将客户的Any视为“ a”。 How do I specify the (ParameterExpression?)type of a? 如何指定a的(ParameterExpression?)类型?
The ParameterReplacer: ParameterReplacer:
class ParameterReplacer : ExpressionVisitor
{
private readonly ParameterExpression parameter;
internal ParameterReplacer(ParameterExpression parameter)
{
this.parameter = parameter;
}
protected override Expression VisitParameter
(ParameterExpression node)
{
return parameter;
}
}
Thanks to the comment of Titian Cernicova-Dragomir I solved it by fixing the ParameterReplacer. 感谢Titian Cernicova-Dragomir的评论,我通过修复ParameterReplacer解决了它。 I added an extra ParameterExpression: 我添加了一个额外的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);
And the ParameterReplacer 和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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.