【问题标题】:Convert Expression to Expression.Lambda<Func<object, bool>>将表达式转换为 Expression.Lambda<Func<object, bool>>
【发布时间】:2016-02-05 04:47:58
【问题描述】:

我有一个基于传递给该方法的对象的类型构建表达式树的方法。构建树后,我想将其转换并返回返回类型,如下所示。

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);
}

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

【问题讨论】:

  • 你能展示一下这个函数的使用示例吗?
  • 当给定错误类型时,表达式应该怎么做?抛出异常?返回false?还有什么?
  • 需要帮助就需要配合。通常Expression&lt;Func&lt;Foo, bool&gt;&gt; 不能被视为Expression&lt;Func&lt;object, bool&gt;&gt;,原因与List&lt;Foo&gt; 不能被视为List&lt;object&gt; 相同。提供真实用例以获得正确的解决方案。
  • 正如伊万指出的那样。在将参数传递给成员表达式之前,您应该使用Expression.Convert(param, type)。并且参数也应该定义为对象 - Expression.Parameter(typeof(Object), "m")

标签: c# lambda expression-trees


【解决方案1】:

这是您的代码,经过我之前的评论中所述的修改。

1) 您的函数返回描述具有单个参数的函数的表达式。这个参数的类型是Object。所以你应该在创建参数“m”表达式时使用Object类型。

2) 在访问属性参数之前,应将其转换回所需的类型。见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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多