为什么要使用防爆pression<&Func键LT; T>>而不是Func键< T&GT ;? [英] Why would you use Expression<Func<T>> rather than Func<T>?

查看:212
本文介绍了为什么要使用防爆pression<&Func键LT; T>>而不是Func键< T&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解lambda表达式和函数功能动作代表。但前pressions难倒我了。在什么情况下你会使用防爆pression< Func键< T>> ,而不是普通的老式 Func键< T>

I understand lambdas and the Func and Action delegates. But expressions stump me. In what circumstances would you use an Expression<Func<T>> rather than a plain old Func<T>?

推荐答案

当你要正确对待拉姆达前pressions如前pression树里面看他们,而不是执行它们。例如,LINQ to SQL中得到前pression并将其转换为等效的SQL语句,并将其提交给服务器(而不是执行拉姆达)。

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).

从概念上讲,防爆pression&LT; Func键&LT; T&GT;&GT; 完全不同的的从 Func键&LT; T&GT ; Func键&LT; T&GT; 表示委托这是pretty多指针的方法和防爆pression&LT;&Func键LT; T&GT;&GT; 表示的树数据结构的一个拉姆达前pression。这种树状结构的描述了一个lambda前pression确实,而不是做实际的事情。它基本上持有约前pressions,变量,方法调用的成分数据,...(例如,它包含的信息,如本拉姆达一些恒定的+一些参数)。您可以使用此说明将其转换为一个实际的方法(用防爆pression.Compile ),或做其他的东西(如LINQ to SQL的例子)它。治疗lambda表达式匿名方法和前pression树木的行为纯粹是一个编译时的事情。

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; }

将有效地编译到IL方法将一无所获,并返回10。

will effectively compile to an IL method that gets nothing and returns 10.

Expression<Func<int>> myExpression = () => 10;

将被转换为一个描述前pression,获取无参数和返回值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.

这篇关于为什么要使用防爆pression&LT;&Func键LT; T&GT;&GT;而不是Func键&LT; T&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆