如何将LambdaExpression转换为带类型的Expression< Func< T,T> [英] How to convert a LambdaExpression to typed Expression<Func<T, T>>

查看:130
本文介绍了如何将LambdaExpression转换为带类型的Expression< Func< T,T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为nHibernate动态构建linq查询。

I'm dynamically building linq queries for nHibernate.

由于依赖关系,我想在以后转换/检索类型化的表达式,但是我一直在

Due to dependencies, I wanted to cast/retrieve the typed expression at a later time, but I have been unsuccessfull so far.

这不起作用(强制转换应该发生在其他地方):

This is not working (the cast is supposed to happen elsewhere):

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获取封装的类型表达式?

Is it possible to get the 'encapsulated' typed expression from a LambdaExpression?

推荐答案

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

这不足为奇,因为您必须 编译 LambdaExpression 为了获得可以调用的实际委托(这是 Func< T,bool> 是的)。

This is not surprising, as you have to Compile a LambdaExpression in order to get an actual delegate that can be invoked (which is what Func<T, bool> is).

所以这行得通,但是我不确定这是否是您所需要的:

So this would work, but I 'm not sure if it is what you need:

// 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>>

If you are not looking to compile the expression but instead to move an expression tree around, then the solution is to instead cast to an Expression<Func<T, bool>>:

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

这篇关于如何将LambdaExpression转换为带类型的Expression&lt; Func&lt; T,T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆