What is the purpose of LINQ's Expression.Quote method?

点点圈 提交于 2019-12-20 09:14:58

问题


The MSDN documentation states:

Expression.Quote

Method Creates a UnaryExpression that represents an expression that has a constant value of type Expression.

I've been able to build predicate expressions for use in LINQ queries by manually constructing them using the Expression class, but have never come across the need for Expression.Quote.

When and why would you use this? From the LINQ expressions I've seen that have them, they just seem to wrap existing expressions without adding any value.

What is the purpose of the Quote method/node type?


回答1:


Expression.Quote specifies that a lambda is to be treated as an expression tree and not as a function. It induces closure semantics on its operand.

When you are constructing a MethodCallExpression using Expression.Call, any parameters that are lambda expressions (LambdaExpression/Expression<TDelegate>) must use Expression.Quote to wrap the parameter before passing in.

So for a parameter of type Expression<Func<bool>>, when you create an instance such as: () => true, the expression's Type property would be Func<bool> whereas the expression's type (calling GetType) would be Expression<Func<bool>>

So to get an Expression that has the correct value for the Type property you pass the lambda expression into Expression.Quote and pass that as the parameter to Expression.Call.

I had a look at Expression.Quote through reflector and while the sole parameter is of type Expression, it must derive from LambdaExpression and this is checked inside the method. Out of interest, anyone know why MS didn't just make the parameter type be LambdaExpression?

As StevenH pointed out, Expression.Quote is used in implementing LINQ Query Providers. All the methods on Queryable that take a lambda expression such as Where, OrderBy, GroupBy, etc internally construct a MethodCallExpression using Expression.Call and wrap the lambda expression parameters with Expression.Quote calls.

For a more detailed explanation of Expression.Quote read this answer.



来源:https://stackoverflow.com/questions/3138133/what-is-the-purpose-of-linqs-expression-quote-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!