问题描述
我了解 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>完全不同.Funcdelegate,它几乎是一个指向方法的指针,而 ExpressionExpression.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 ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)