Why would you use Expressionlt;Funclt;Tgt;gt; rather than Funclt;Tgt;?(为什么要使用表达式lt;Funclt;Tgt;gt;而不是 Func T ?)
问题描述
我了解 lambda 以及 Func
和 Action
委托.但是表达式难倒我.
I understand lambdas and the Func
and Action
delegates. But expressions
stump me.
在什么情况下你会使用 Expression<Func<T>>
而不是普通的旧 Func<T>
?
In what circumstances would you use an Expression<Func<T>>
rather than a plain old Func<T>
?
推荐答案
当您想将 lambda 表达式视为表达式树并查看它们内部而不是执行它们时.例如,LINQ to SQL 获取表达式并将其转换为等效的 SQL 语句并将其提交给服务器(而不是执行 lambda).
When you want to treat lambda expressions as expression trees and look inside them instead of executing them. For example, LINQ to SQL gets the expression and converts it to the equivalent SQL statement and submits it to server (rather than executing the lambda).
从概念上讲,Expression<Func<T>>
与 Func<T>
完全不同.Func
delegate
,它几乎是一个指向方法的指针,而 Expression
Expression.Compile
)或使用它执行其他操作(如 LINQ to SQL 示例).将 lambdas 视为匿名方法和表达式树的行为纯粹是编译时的事情.
Conceptually, Expression<Func<T>>
is completely different from Func<T>
. Func<T>
denotes a delegate
which is pretty much a pointer to a method and Expression<Func<T>>
denotes a tree data structure for a lambda expression. This tree structure describes what a lambda expression does rather than doing the actual thing. It basically holds data about the composition of expressions, variables, method calls, ... (for example it holds information such as this lambda is some constant + some parameter). You can use this description to convert it to an actual method (with Expression.Compile
) or do other stuff (like the LINQ to SQL example) with it. The act of treating lambdas as anonymous methods and expression trees is purely a compile time thing.
Func<int> myFunc = () => 10; // similar to: int myAnonMethod() { return 10; }
将有效地编译成一个什么都不得到并返回 10 的 IL 方法.
will effectively compile to an IL method that gets nothing and returns 10.
Expression<Func<int>> myExpression = () => 10;
将被转换为描述一个没有参数并返回值10的表达式的数据结构:
will be converted to a data structure that describes an expression that gets no parameters and returns the value 10:
虽然它们在编译时看起来相同,但编译器生成的却完全不同.
While they both look the same at compile time, what the compiler generates is totally different.
这篇关于为什么要使用表达式<Func<T>>而不是 Func T ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么要使用表达式<Func<T>>而不是 Func T ?
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01