【问题标题】:Expression of type 'System.Func`2[T,System.Boolean]' cannot be used for return type 'System.Boolean''System.Func`2[T,System.Boolean]' 类型的表达式不能用于返回类型 'System.Boolean'
【发布时间】:2020-04-02 08:01:17
【问题描述】:

您好,我在将我的表达式转换为 Expression<Func<T, bool>> 时遇到问题。这可能吗? Expression.Lambda 调用因Expression of type 'System.Func`2[T,System.Boolean]' cannot be used for return type 'System.Boolean' 而出错,这对我来说没有意义,因为我认为函数具有匹配的返回类型?

Expression expression = serializer.DeserializeText(serializedText);
ParameterExpression entityType = Expression.Parameter(typeof(T));
Expression<Func<T, bool>> typedExpression = Expression.Lambda<Func<T, bool>>(expression, entityType);

编辑:表达式是一个强类型的 lambda,例如s => idArray.Contains(s.SomeIntColumn) 其中 s 是 T 类型。然后使用 LINQ 序列化程序对表达式进行序列化,然后将其反序列化为 System.Linq.Expression。因为我知道它是 T 类型的函数,返回 bool,所以我想强输入它。

【问题讨论】:

  • expression 是什么类型?
  • 这里的serializer.DeserializeText(serializedText) 是什么?没有完整的上下文很难评论,但请注意它根本没有使用 lambda 参数
  • 那么表达式已经是LambdaExpression了吗?
  • 请查看编辑。是的,它是一个 lambda 表达式。序列化之前是 Expression>.

标签: c# lambda


【解决方案1】:

不确定您的 sn-p 中的 serializedText 是什么,但只要它是返回 booleanLambdaExpression,您应该能够执行以下操作。

  Expression expression = Expression.Lambda(Expression.Constant(true), Expression.Parameter(typeof(string)));

  Expression<Func<string, bool>> typedExpression = (Expression<Func<string, bool>>)(expression);

  Console.WriteLine(typedExpression.Compile().Invoke("Hello"));

用你的泛型类型替换string

在您的示例中,如果可以将 serializedText 反序列化为 Expression,则以下内容应该可以工作,您必须根据自己的考虑对其进行更改。

Expression<Func<T, bool>> typedExpression = (Expression<Func<T, bool>>)Expression.Lambda(
                                                                        serializer.DeserializeText(serializedText), 
                                                                        Expression.Parameter(typeof(T)));

【讨论】:

  • 这取决于。如果 OP 正在从另一个 lambda 构造 lambda,则有时需要更新参数。喜欢o.Method() 需要更新为x =&gt; x.Method()
猜你喜欢
  • 1970-01-01
  • 2016-09-20
  • 2011-01-13
  • 2013-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
相关资源
最近更新 更多