How to convert a LambdaExpression to typed Expression<Func<T, T>>

巧了我就是萌 提交于 2020-01-12 04:24:25

问题


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

This is working:

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

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


回答1:


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

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();

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);


来源:https://stackoverflow.com/questions/16213005/how-to-convert-a-lambdaexpression-to-typed-expressionfunct-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!