如何将LambdaExpression转换为类型化表达式<Func >
我正在为nHibernate动态构建linq查询。
由于依赖关系,我想在以后转换/检索键入的表达式,但到目前为止我还没有成功。
这不起作用(演员应该发生在其他地方):
var funcType = typeof (Func).MakeGenericType(entityType, typeof (bool)); var typedExpression = (Func)Expression.Lambda(funcType, itemPredicate, parameter); //Fails
这是有效的:
var typedExpression = Expression.Lambda<Func>(itemPredicate, parameter);
是否有可能从LambdaExpression获取’封装’类型表达式?
var typedExpression = (Func)Expression.Lambda(funcType, itemPredicate, parameter); //Fails
这并不奇怪,因为您必须Compile
LambdaExpression
才能获得可以调用的实际委托(这就是Func
)。
所以这可行,但我不确定它是否是你需要的:
// This is no longer an expression and cannot be used with IQueryable var myDelegate = (Func) Expression.Lambda(funcType, itemPredicate, parameter).Compile();
如果您不是要编译表达式而是要移动表达式树,那么解决方案是转换为Expression
:
var typedExpression = (Expression>) Expression.Lambda(funcType, itemPredicate, parameter);