Expression.Or - 变量' a'类型'预约'从范围''引用,但未定义

时间:2014-04-23 12:15:51

标签: c# lambda expression-trees func

我尝试连接两个表达式,但在编译方法的标题中提到了错误:

 Expression<Func<Appointment, bool>> week1 = StartDateIsBetween(lastMonday, nextSunday);
 Expression<Func<Appointment, bool>> week2 = EndDateIsBetween(lastMonday, nextSunday);
 BinaryExpression weekOr = Expression.Or(week1.Body, week2.Body);

 Func<Appointment, bool> week = Expression.Lambda<Func<Appointment, bool>>(weekOr, week1.Parameters.Single()).Compile();

另外两种创建表达式的方法:

 private Expression<Func<Appointment, bool>> StartDateIsBetween(DateTime beginningDate, DateTime endDate)
    {
        return a => a.StartDate >= beginningDate && a.StartDate <= endDate;
    }

    private Expression<Func<Appointment, bool>> EndDateIsBetween(DateTime beginningDate, DateTime endDate)
    {
        return a => a.EndDate >= beginningDate && a.EndDate <= endDate;
    }

知道如何修复此错误吗?我是表达树的初学者:/

1 个答案:

答案 0 :(得分:3)

week1week2具有不同的参数,因为它们是单独创建的。最简单的方法是在现有表达式上使用ExpressionInvoke,使用新的ExpressionParameter实例:

var param = Expression.Parameter(typeof(Appointment));
var weekOr = Expression.Or(Expression.Invoke(week1, param), Expression.Invoke(week2, param));

var week = Expression.Lambda<Func<Appointment, bool>>(weekOr, param).Compile();