[英]How to convert Func<T,bool> to Expression<Func<T,bool>>
I have a Func like this : 我有这样的Func:
Func<MyClass, bool> func = x=>Id == 5;
How I can convert it to : 我如何将其转换为:
Expression<Func<MyClass, bool>>
You can just write: 你可以写:
Expression<Func<MyClass,bool>> expr = x=>Id == 5;
This will set expr
to be an expression tree for Id == 5
. 这会将
expr
设置为Id == 5
的表达式树。
If you do: 如果你这样做:
Func<MyClass, bool> func = x=>Id == 5;
Expression<Func<MyClass, bool>> expr = mc => func(mc);
Then this will set expr
to be an expression tree for a call to func
, not an expression tree for the body of func
. 然后,这将把
expr
设置为调用func
的表达式树,而不是func
体的表达式树。
Try this: 试试这个:
Func<MyClass, bool> func = x=>Id == 5;
Expression<Func<MyClass, bool>> expr = mc => func(mc);
You can create an expression that represents the call to the delegate you created. 您可以创建表示对您创建的委托的调用的表达式。 But most of the time, when you're using
Expression
s, you do that to understand what the code does (eg to convert it to SQL). 但大多数情况下,当您使用
Expression
,您可以这样做以了解代码的作用(例如,将其转换为SQL)。 And you can't do that with an expression to invoke an opaque function. 你不能用表达式来调用不透明的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.