在 C# 中,为什么使用表达式树以及何时需要使用它们?
当我需要 表达式树 时?
如果有的话,请向我们提供真实世界的样本
When I need the Expression Trees ?
And please provide us with a real world sample if available
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
例如,要实现 INotifyPropertyChanged 的类型安全实现,而不是使用字符串:
For example to implement a typesafe implementation of INotifyPropertyChanged instead of using strings:
每当您想要告诉某个函数需要做什么而不是实际执行时,您都需要一个表达式树。
主要的例子是 LINQ-to-SQL。您传递一个表达式树,以便它可以将此表达式树转换为 SQL。它不会执行表达式,而是检查表达式并将其转换为 SQL。
You need an expression tree every time you want to tell some function what needs to be done instead of actually doing it.
The prime example is LINQ-to-SQL. You pass an expression tree so that it can translate this expression tree into SQL. It doesn’t execute the expression, it examines it and translates it to SQL.
表达式树是一些执行的描述——实际上它是 DOM。当您执行表达式树时,它会被编译并随后执行。示例是 LinqToSql。当您为 LinqToSql 构建查询时,您是在 IQueryable 上执行的。结果查询是表达式树。当您执行树时,它会被“编译”为 SQL 而不是 .NET 并在数据库上执行。
编辑: 这里是另一个很好的表达式示例,用于在 EF 查询中包含相关实体。
Expression tree is description of some execution - actually it is DOM. When you execute expression tree it is compiled and after that executed. Example is LinqToSql. When you build query for LinqToSql you are doing it on the IQueryable. Resulting query is expression tree. When you execute the tree it is "compiled" into SQL instead of .NET and executed on database.
Edit: Here you have another nice example of Expression used for including related entities in EF query.
我最近重构了一个复杂的对象比较器并使用了表达式树。
对象比较器是使用反射实现的,我将其修改为使用反射构建表达式树,然后将表达式树编译为委托。构建和编译委托需要一些费用,但编译后,调用速度几乎比反射解决方案快 100 倍。
I recently refactored a complex object comparer and used expression trees.
The object comparer had been implemented using reflection, and I modified it to instead build an expression tree using reflection, then compile the expression tree into a delegate. There is a bit of expense to build and compile the delegate, but after it is compiled it is almost 100x faster to call than the reflected solution.