在使用 .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/