有点好奇,以了解.NET中的表达式树 [英] Bit Curious to understand Expression Tree in .NET

查看:111
本文介绍了有点好奇,以了解.NET中的表达式树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了几篇关于表达式的文章和几篇关于表达式树的帖子。
这是我的大脑了解。

I have read several articles and several stackoverflow.com posts about expression tree. It is beating my brain to understand.

问题:


1)像DOM(文档对象模型)一样,它是逻辑内存中的表示形式?

1) Like DOM (Document Object Model), it is an in-memory representation of logic?

2)有人解释说将可执行代码转换为数据的机制,使用它可以生成代表代码的数据结构。

2) Somebody explained it is a mechanism to translate an executable code into data, using it we can produce a data structure representing the code.

是否意味着表达式树用于设计用户定义的模式?

Does it mean, expression trees are used to design a user defined pattern?

3)大多数示例显示表达式树与 Func 委托或其他代表结合使用,所以使用委托和其他编程结构不能实现与表达式服务相同的事情。

3) Most of the Examples show Expression tree in conjunction with Func<> delegate or other delegates, So using delegate and other programming construct can’t we achieve the same thing as expression tree serves.

非常感谢初学者可以理解的解释。

Beginners-understandable explanation is highly appreciated.

推荐答案

表达式树表示单个表达式的语法树。

Expression tree represent a syntax tree of a single expression.

树的每个节点表示一些常量,对象成员引用或操作。

Each node of tree represent some constant, object member reference or operation.

例如。对于表达式 2 + 3 我们可以构建和表达树:

E.g. for expression 2 + 3 we can build and expression tree:

Expression.MakeBinary(
    ExpressionType.Add,
    Expression.Constant(2),
    Expression.Constant(3));

最重要的这样的树是Expression,它允许以漂亮的可读形式写入表达式,提醒lambda函数签名匹配TDelegate。这里是

The most important of such trees is Expression which allows to write expression in nice readable form reminding lambda functions of signature matching TDelegate. Here's ex

Expression<Func<int>> sum = () => 2 + 3; // much nicer, eh?

但表达式不是委派的,因为它不能被直接执行。

But Expression is not delegate, since it couldn't be executed directly.

相反,它可以遍历例如与访客对象构建一些可执行表示。示例可以是使用Expression.Compile()或使用CompiledQuery.Compile()等从LINQ查询构建的SQL查询来委托构建。

Instead it can be traversed e.g. with visitor object to build some executable representation. Examples could be delegate build with Expression.Compile() or SQL query built from LINQ query using CompiledQuery.Compile() etc.

表达式树的另一个有用的应用程序正在使用它们来表示否则将需要使用Reflection的对象的成员。反射使用字符串来表示成员名称,在编译时不进行检查。表单树被检查,所以可以少一点错误。

Another useful application of expression trees is using them to represent members of objects that otherwise would require usage of Reflection. Reflection uses strings to represent member names and makes no checks at compile time. Expression trees are checked, so a little less errors could be made.

PropertyInfo prop1 = typeof(MyClass).GetProperty("Value");

Expression<Func<MyClass, int>> expr = mc => mc.Value;
PropertyInfo prop2 = (mc.Body as MemberExpression).Member as PropertyInfo;

这篇关于有点好奇,以了解.NET中的表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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