.net - 表达式树有什么好处?

标签 .net expression-trees

在使用 .Net 语言开发应用程序时,我没有得到表达式树的使用或好处?真的有必要吗?

最佳答案

表达式树允许您在常规 C# 中表达您的代码,但可以对其进行解构、检查和解释。例如,您可以通过编写等效的 TSQL 字符串(例如:LINQ-to-SQL 或 Entity Framework )或 Web 服务查询 (astoria) 来解释它。您可能会将其解释为 RPC 调用(我编写了一个基于表达式的 RPC 层)。

重复my "Explaining Expression" blog entry :

  • The delegate version (Func<int,int,bool>) is the beligerant manager; "I need you to give me a way to get from 2 integers to a bool; I don't care how - when I'm ready, I'll ask you - and you can tell me the answer".
  • The expression version (Expr<Func<int,int,bool>>) is the dutiful analyst; "I need you to explain to me - if I gave you 2 integers, how would you go about giving me a bool?"


如果你有这个表达式,你可以调用Compile()形成一个代表(完全按照解释做),或者你可以取消它并根据他们采取的步骤做类似的事情。

关于 Expression 的另一种观点是它可以作为 ILGenerator 的简化版本- 但仍然非常多才多艺。对于元编程非常有用。这里是 an article exploring that approach .

关于.net - 表达式树有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5830809/

相关文章:

c# - 为使用 IoC.Resolve() 的服务创建单元测试的最佳方法是什么

c# - SetWindowPos/MoveWindow 持续存在问题

c# - 在运行时创建具有通用接口(interface)的通用类型

c# - Expression.Reduce() 是做什么的?

algorithm - 根据霍纳方案,将多项式的解析树转换为其评估的解析树

c# - 从范围 '' 引用类型为 '' 的变量 '',但未定义

c# - 我需要每天花好几个小时尽可能快地发送大量 Web 请求。什么是最有效的方法?

jquery - .NET 4.5 中 MSAjax 和 WebFormsJS 的文档在哪里?

c# - 从服务端访问 WCF 身份验证信息

c# - 使用 lambda 表达式从 Controller 获取操作