C# 如何将LambdaExpression转换为类型化表达式<;Func<;T、 T>&燃气轮机;
我正在为nHibernate动态构建linq查询 由于依赖关系,我想稍后强制转换/检索类型化表达式,但到目前为止没有成功 这不起作用(演员应该在其他地方进行):C# 如何将LambdaExpression转换为类型化表达式<;Func<;T、 T>&燃气轮机;,c#,.net,casting,lambda,linq-expressions,C#,.net,Casting,Lambda,Linq Expressions,我正在为nHibernate动态构建linq查询 由于依赖关系,我想稍后强制转换/检索类型化表达式,但到目前为止没有成功 这不起作用(演员应该在其他地方进行): var funcType=typeof(Func).MakeGenericType(entityType,typeof(bool)); var typedExpression=(Func)表达式.Lambda(funcType,itemperedicate,parameter)//失败 这是有效的: var typedExpressi
var funcType=typeof(Func).MakeGenericType(entityType,typeof(bool));
var typedExpression=(Func)表达式.Lambda(funcType,itemperedicate,parameter)//失败
这是有效的:
var typedExpression = Expression.Lambda<Func<T, bool>>(itemPredicate, parameter);
var typedExpression=Expression.Lambda(itemPredicate,参数);
是否可以从LambdaExpression获取“封装”类型的表达式
var typedExpression =
(Func<T, bool>)Expression.Lambda(funcType, itemPredicate, parameter); //Fails
如果您不希望编译表达式,而是希望移动表达式树,那么解决方案是转换为表达式
:
var typedExpression=(表达式)
Lambda表达式(funcType、itemPredicate、parameter);
也许您正在查找typedExpression.Compile(),我需要将该表达式用作ORM映射器的IQueryable,以便无法对其进行编译。感谢您的回复。是的,我正在寻找移动表达式树。问题在于您所引用的类型转换Expression typedExpression=Expression.Lambda(funcType、itemPredicate、parameter)
这导致无法将源类型System.Linq.Expressions.LambdaExpression转换为目标类型System.Linq.Expressions.Expression
@Larantz:对不起,我的错误;我忘了你需要明确地施法。查看更新的答案。谢谢。我真不敢相信我竟如此盲目地没有注意到我缺少cast的表达式部分:)。显式castvar-typedExpression=(表达式)(…)
解决了我类似的问题。
var typedExpression =
(Func<T, bool>)Expression.Lambda(funcType, itemPredicate, parameter); //Fails
// This is no longer an expression and cannot be used with IQueryable
var myDelegate =
(Func<T, bool>)
Expression.Lambda(funcType, itemPredicate, parameter).Compile();
var typedExpression = (Expression<Func<T, bool>>)
Expression.Lambda(funcType, itemPredicate, parameter);