从 Func 创建表达式 [英] Create Expression from Func
问题描述
我的代码中有一个 Func
.我用它来选择某些属性.
I have a Func<TCollection, T>
in my code. I use it to select certain properties.
在调用另一个方法时,我需要 Expression
作为参数.
In a call to another method I need Expression<Func<TCollection, T>>
as a parameter.
有什么方法可以将Func
转换(或创建自)Expression
?
Is there any way to convert (or create from) Func<TCollection, T>
to Expression<Func<TCollection, T>>
?
谢谢
推荐答案
您不能基于方法重新创建表达式,因为表达式需要知道原始语句,而不是 IL.但是,您可以创建一个 Expresson,它对您的 func 进行方法调用,例如:
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));
但是请注意,像 EF 这样的系统无法真正使用此功能
Note however that systems like EF can't really work with this
这篇关于从 Func 创建表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!