首页 > 解决方案 > 'System.Func`2[T,System.Boolean]' 类型的表达式不能用于返回类型 'System.Boolean'

问题描述

嗨,我在将我的 Expression 转换为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 类型的函数,所以我想强输入它。

标签: c#lambda

解决方案


不确定serializedText您的代码段中是什么,但只要它是 aLambdaExpression返回 aboolean您应该能够执行以下操作。

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

推荐阅读