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

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

问题描述

我了解 lambda 以及 FuncAction 委托.但是表达式难倒我.

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 表示一个 树数据结构 用于 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; }

将有效地编译成一个什么都不得到并返回 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.

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

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