-->

What is the purpose of LINQ's Expression.Quote

2019-03-09 04:19发布

问题:

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.