为什么要使用表达式< Func< T>而不是Func< T> [英] Why would you use Expression<Func<T>> rather than Func<T>?

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

问题描述

我知道lambdas和 Func Action 代表。但是表情让我失望了在什么情况下,您将使用表达式< 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>?

推荐答案

当您想要将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).

从概念上讲, c $ c> 与 Func< T> 完全不同。 Func< T> 表示一个委托,它几乎是一个方法的指针, Expression< ; Func< T> 表示lambda表达式的树数据结构。这个树结构描述了一个lambda表达式,而不是做实际的事情。它基本上保存有关表达式,变量,方法调用的组合的数据...(例如,它保存诸如此lambda的信息是一些常量+一些参数)。您可以使用此描述将其转换为实际的方法(使用 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; }

将有效地编译为无法获取任何内容的IL方法,并返回10。

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.

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

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