我理解lambdas和Func和Action委托。但表情 我头疼不已。
在什么情况下,你会使用表达式<Func<T>>而不是普通的旧Func<T>?
我理解lambdas和Func和Action委托。但表情 我头疼不已。
在什么情况下,你会使用表达式<Func<T>>而不是普通的旧Func<T>?
当前回答
主要原因是当您不想直接运行代码,而是想检查它时。这可能有很多原因:
Mapping the code to a different environment (ie. C# code to SQL in Entity Framework) Replacing parts of the code in runtime (dynamic programming or even plain DRY techniques) Code validation (very useful when emulating scripting or when doing analysis) Serialization - expressions can be serialized rather easily and safely, delegates can't Strongly-typed safety on things that aren't inherently strongly-typed, and exploiting compiler checks even though you're doing dynamic calls in runtime (ASP.NET MVC 5 with Razor is a nice example)
其他回答
这是我的两分钱…
Func<T> =一个刚被执行的委托/方法,仅此而已。 表达式<Func<T>> =转换为另一种形式。例如,LINQ to Entities表达式被转换为等效的SQL查询。
想象一下,两者看起来很相似,但表达式就像一个数据结构,具有反射的能力。编译器实际上知道关于它的签名和主体的所有信息(类似于类反射)。利用这些知识,表达式被转换为其他形式,就像LINQ被转换为SQL查询一样。
现在,还有另一个角度来处理IQueryable行为。建议您始终传递LINQ的Expression to Where或Count方法,以便您的查询过滤器在SQL server上运行,而不是在内存中提取数据然后进行过滤。
当您希望将函数视为数据而不是代码时,可以使用表达式。如果您想操作代码(作为数据),可以这样做。大多数情况下,如果你认为不需要表达式,那么你可能就不需要使用表达式。
我想补充一些关于Func<T>和Expression<Func<T>>的区别:
Func<T> is just a normal old-school MulticastDelegate; Expression<Func<T>> is a representation of lambda expression in form of expression tree; expression tree can be constructed through lambda expression syntax or through the API syntax; expression tree can be compiled to a delegate Func<T>; the inverse conversion is theoretically possible, but it's a kind of decompiling, there is no builtin functionality for that as it's not a straightforward process; expression tree can be observed/translated/modified through the ExpressionVisitor; the extension methods for IEnumerable operate with Func<T>; the extension methods for IQueryable operate with Expression<Func<T>>.
有一篇文章用代码示例描述了细节: LINQ: Func<T> vs. Expression<Func<T>>。
希望对大家有所帮助。
这里过于简化了,但Func是一个机器,而Expression是一个蓝图。: D
主要原因是当您不想直接运行代码,而是想检查它时。这可能有很多原因:
Mapping the code to a different environment (ie. C# code to SQL in Entity Framework) Replacing parts of the code in runtime (dynamic programming or even plain DRY techniques) Code validation (very useful when emulating scripting or when doing analysis) Serialization - expressions can be serialized rather easily and safely, delegates can't Strongly-typed safety on things that aren't inherently strongly-typed, and exploiting compiler checks even though you're doing dynamic calls in runtime (ASP.NET MVC 5 with Razor is a nice example)