将表达式转换为Expression.Lambda <func <object,bool =“”>&gt;

时间:2016-02-04 16:24:02

标签: c# lambda expression-trees

我有一个方法,根据传递给方法的对象的类型构建表达式树。一旦构建了树,我想转换它并返回它,返回类型如下所示。

public static Expression<Func<object, bool>> BuildExpression(Type type, ...)
{
    // build the expression...
    ParameterExpression param = Expression.Parameter(type, "m");
    Expression expression = null;

    // simplified version of building the expression tree
    MemberExpression member = Expression.Property(param, filter.Property);
    ConstantExpression constant = Expression.Constant(filter.Value);
    expression = Expression.Equal(member, constant);

   // ...

   // IT FAILS ON THIS LINE!!!
   return Expression.Lambda<Func<object, bool>>(expression, param);
}

我看了一些转换答案,但无济于事。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

以下是我之前评论中所述的修改代码。

1)您的函数返回用单个参数描述函数的表达式。此参数的类型为Object。因此,在创建参数时,您应该使用Object类型&#34; m&#34;表达。

2)在访问property参数之前,应该将其转换回所需的类型。请参阅Expression.Convert

public static Expression<Func<object, bool>> BuildExpression(Type type, ...)
{
    // build the expression...
    ParameterExpression param = Expression.Parameter(typeof(Object), "m");
    Expression expression = null;

    UnaryExpression convert = Expression.Convert(param, type);

    // simplified version of building the expression tree
    MemberExpression member = Expression.Property(convert, filter.Property);
    ConstantExpression constant = Expression.Constant(filter.Value);
    expression = Expression.Equal(member, constant);

    // ...

    return Expression.Lambda<Func<object, bool>>(expression, param);
}