【问题标题】:How to convert a LambdaExpression to typed Expression<Func<T, T>>如何将 LambdaExpression 转换为类型化的 Expression<Func<T, T>>
【发布时间】:2013-04-19 05:52:13
【问题描述】:

我正在为 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 中获取“封装”类型的表达式?

【问题讨论】:

  • 也许你正在寻找 typedExpression.Compile()
  • 我需要将表达式作为 IQueryable 与我的 ORM 映射器一起使用,因此无法编译。

标签: c# .net casting lambda linq-expressions


【解决方案1】:
var typedExpression =
    (Func<T, bool>)Expression.Lambda(funcType, itemPredicate, parameter); //Fails

这并不奇怪,因为您必须 CompileLambdaExpression 才能获得可以调用的实际委托(Func&lt;T, bool&gt; 就是这样)。

所以这会起作用,但我不确定它是否是你需要的:

// This is no longer an expression and cannot be used with IQueryable
var myDelegate =
    (Func<T, bool>)
    Expression.Lambda(funcType, itemPredicate, parameter).Compile();

如果您不希望编译表达式而是移动表达式树,则解决方案是转换为 Expression&lt;Func&lt;T, bool&gt;&gt;:

var typedExpression = (Expression<Func<T, bool>>) 
                      Expression.Lambda(funcType, itemPredicate, parameter);

【讨论】:

  • 感谢您的回复。是的,我正在寻找移动表达式树。问题是你提到的演员Expression&lt;Func&lt;T, bool&gt;&gt; typedExpression = Expression.Lambda(funcType, itemPredicate, parameter);这导致Cannot convert souce type System.Linq.Expressions.LambdaExpression to target type System.Linq.Expressions.Expression&lt;System.Func&lt;MyType, object&gt;&gt;
  • @Larantz:对不起,我的错;我忘了你需要明确地投射。查看更新后的答案。
  • 谢谢。我无法相信我是多么盲目地没有注意到我缺少演员表中的 Expression 部分:)。
  • 显式转换 var typedExpression = (Expression&lt;Func&lt;T, bool&gt;&gt;) (...) 解决了我的类似问题。
猜你喜欢
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多