我被困在一个只有一个 int
参数和一个 bool
返回值的 lambda 上:
Expression<Func<int, bool>> myFunc = x => x == 5;
首先,我尝试了返回一个我无法理解的新 Func
的方法;我期待一个 true
bool 值:
var boolResult = Expression.Lambda(myFunc).Compile().DynamicInvoke(5);
然后我尝试显式设置函数参数和返回类型:
var param = Expression.Parameter(typeof(int), "x");
var fn = Expression.Lambda<Func<int, bool>> (myFunc, param).Compile();
,但这会引发错误:
System.ArgumentException : Expression of type 'System.Func`2[System.Int32,System.Boolean]' cannot be used for return type 'System.Boolean'
这很奇怪,但我尝试转换表达式:
var fn = Expression.Lambda<Func<int, bool>> (
Expression.Convert(myFunc,
typeof(Func<int, bool>))
, param).Compile();
var boolResult = fn.Invoke(5);
,但这并没有帮助并给出了同样的错误:
System.ArgumentException : Expression of type 'System.Func`2[System.Int32,System.Boolean]' cannot be used for return type 'System.Boolean'
知道我在这里做错了什么吗?
最佳答案
动态调用代码中的错误是您构建 lambda 的方式。当你通过 myFunc
作为表达式,你得到一个返回 Func<int,bool>
的 lambda .
如果你想制作一个新的LambdaExpression
这需要 int
并返回 bool
, 你可以收获 Body
和 Parameters
你的myFunc
对象,像这样:
var b = Expression.Lambda(myFunc.Body, myFunc.Parameters).Compile().DynamicInvoke(5);
或者,自 myFunc
已经是 LambdaExpression
,你可以直接编译它:
var c = myFunc.Compile().DynamicInvoke(6);
关于c# - 卡在简单的单参数 lambda 和 bool 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37772758/