c# - '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 类型的函数,所以我想强输入它。
解决方案
不确定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)));
推荐阅读
- python - NameError:名称“捕获”未定义
- javascript - 如何修复:“您的 SQL 语法有错误”
- mysql - Laravel:表内容更改,如何更新现有数据库外键
- nmap - 大 IP 范围上的 Nmap 扫描不显示主机名
- filter - Magento 2.3 管理过滤器 - 输入后日期列未清除
- node.js - 错误.. [ERR_REQUIRE_ESM]:必须使用导入来加载 ES 模块
- rust - 无法将具有任意长度切片的数组传递给 From 特征
- react-native - 在反应本机中单击位于其外部的按钮时更改 Flatlist 的项目
- swift - NSTableCellView 对焦环
- vba - 如何查找特定 ID MS 项目