从Func创建表达式 [英] Create Expression from Func

查看:95
本文介绍了从Func创建表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有一个 Func< TCollection,T> 。我使用它来选择某些属性。



在调用另一个方法时,我需要 Expression< Func< TCollection,T>> 作为参数。



是否有任何方法可以转换(或创建) Func< TCollection,T> to 表达式< Func< TCollection,T>>< / code>< / p>

$ b

解决方案

因为表达式需要知道原始语句而不是IL,所以不能重新创建基于方法的表达式。然而,你可以创建一个Expresson,它可以调用你的func方法,例如:

  Func< int> func =()=> 1; 
表达式< Func< int>> expression = Expression.Lambda< Func< int>>(Expression.Call(func.Method));

请注意,像EF这样的系统无法真正处理这个


I have a Func<TCollection, T> in my code. I use it to select certain properties.

In a call to another method I need Expression<Func<TCollection, T>> as a parameter.

Is there any way to convert (or create from) Func<TCollection, T> to Expression<Func<TCollection, T>> ?

Thanks

解决方案

You can not recreate an expression based on a method since an expression needs to know the original statements, not IL. You can however create an Expresson which makes a method call to your func like:

Func<int> func = () => 1;
Expression<Func<int>> expression = Expression.Lambda<Func<int>>(Expression.Call(func.Method));

Note however that systems like EF can't really work with this

这篇关于从Func创建表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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