简体   繁体   English

如何转换Func <T,bool> 表达 <Func<T,bool> &gt;

[英]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.

相关问题 转换表达式 <Func<T,T,bool> &gt;表达 <Func<T,bool> &gt; - Convert Expression<Func<T,T,bool>> to Expression<Func<T,bool>> 是否可以转换表达式 <Func<T, bool> &gt;表达 <Func<MyType, bool> &gt;? - Is it possible to convert Expression<Func<T, bool>> to Expression<Func<MyType, bool>>? 如何转换表达式 <Func<T1, bool> &gt;表达 <Func<T2, bool> &gt; - How to convert Expression<Func<T1, bool>> to Expression<Func<T2, bool>> 如何转换 Linq 表达式<func<object,object,bool> &gt; 表达<func<t1,t2,bool> &gt; </func<t1,t2,bool></func<object,object,bool> - How to convert Linq Expression<Func<object,object,bool>> to Expression<Func<T1,T2,bool>> 将表达式转换为表达式 <Func<T, bool> &gt; - Convert Expression to Expression<Func<T, bool>> 转换谓词 <T> 表达 <Func<T, bool> &gt; - Convert Predicate<T> to Expression<Func<T, bool>> C#-如何转换Func <T, bool> 到功能 <dynamic, bool> ? - C# - How to convert Func<T, bool> to Func<dynamic, bool>? 如何转换IQueryable <T> 表达 <Func<T, bool> &gt;? - How to convert IQueryable<T> to Expression<Func<T, bool>>? 如何将Expression <Func <T,bool >>转换为Predicate <T> - How to convert an Expression<Func<T, bool>> to a Predicate<T> 如何构建表达式 <Func<T,bool> &gt;来自表达 <Func<T> &gt; - How to build Expression<Func<T,bool>> from Expression<Func<T>>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM