我正在为 nHibernate 动态构建 linq 查询。
由于依赖性,我想稍后转换/检索键入的表达式,但到目前为止我还没有成功。
这是行不通的(演员应该在其他地方发生):
var funcType = typeof (Func<,>).MakeGenericType(entityType, typeof (bool));
var typedExpression = (Func<T, bool>)Expression.Lambda(funcType, itemPredicate, parameter); //Fails
这是工作:
var typedExpression = Expression.Lambda<Func<T, bool>>(itemPredicate, parameter);
是否可以从 LambdaExpression 获取“封装的”类型表达式?
var typedExpression =
(Func<T, bool>)Expression.Lambda(funcType, itemPredicate, parameter); //Fails
这并不奇怪,因为你必须Compile http://msdn.microsoft.com/en-us/library/bb356928.aspx a LambdaExpression
为了获得可以调用的实际委托(这就是Func<T, bool>
is).
所以这可行,但我不确定这是否是您所需要的:
// This is no longer an expression and cannot be used with IQueryable
var myDelegate =
(Func<T, bool>)
Expression.Lambda(funcType, itemPredicate, parameter).Compile();
如果您不想编译表达式而是要移动表达式树,那么解决方案是转换为Expression<Func<T, bool>>
:
var typedExpression = (Expression<Func<T, bool>>)
Expression.Lambda(funcType, itemPredicate, parameter);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)