C# 什么是表达式树,如何使用它们,为什么要使用它们?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10005948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:06:03  来源:igfitidea点击:

What are Expression Trees, how do you use them, and why would you use them?

c#.netlinqexpression-trees

提问by Donny

I just came across the concept of expression trees which I have heard multiple times. I just want to understand what is meant by an expression tree and its purpose.

我刚刚遇到了我多次听到的表达树的概念。我只想了解表达式树的含义及其目的。

I would love it if someone could also direct me to simple explanations and samples of use.

如果有人也可以指导我进行简单的解释和使用示例,我会很高兴的。

采纳答案by Roy Dictus

An Expression Tree is a data structure that contains Expressions, which is basically code. So it is a tree structure that represents a calculation you may make in code. These pieces of code can then be executed by "running" the expression tree over a set of data.

表达式树是一种包含表达式的数据结构,它基本上是代码。所以它是一个树结构,表示您可以在代码中进行的计算。然后可以通过在一组数据上“运行”表达式树来执行这些代码段。

A great thing about expression trees is that you can build them up in code; that is, you build executable code (or a sequence of steps) in code. You can also modify the code before you execute it by replacing expressions by other expressions.

表达式树的一大优点是您可以在代码中构建它们;也就是说,您在 code 中构建可执行代码(或一系列步骤)。您还可以在执行之前修改代码,方法是用其他表达式替换表达式。

An Expression is then a function delegate, such as (int x => return x * x).

一个表达式则是一个函数委托,例如(int x => return x * x).

See also http://blogs.msdn.com/b/charlie/archive/2008/01/31/expression-tree-basics.aspx

另见http://blogs.msdn.com/b/charlie/archive/2008/01/31/expression-tree-basics.aspx