What does Expression.Quote() do that Expression.Constant() can’t already do?

后端 未结 5 847
执笔经年
执笔经年 2020-12-04 05:51

Note: I am aware of the earlier question “What is the purpose of LINQ\'s Expression.Quote method?”, but if you read on you will see that it doesn’t answer m

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 06:39

    After this a really excellent answer, it's clear what are the semantics. It's not so clear why they are designed that way, consider:

    Expression.Lambda(Expression.Add(ps, pt));
    

    When this lambda is compiled and invoked it evaluates the inner expression and returns the result. Inner expression here is an addition, so the ps+pt is evaluated and the result is returned. Following this logic, the following expression:

    Expression.Lambda(
        Expression.Lambda(
                  Expression.Add(ps, pt),
                pt), ps);
    

    should return an inner's lambda compiled method reference when the outer lambda is invoked (because we say that lambda compiles to a method reference). So why do we need a Quote?! To differentiate the case when the method reference is returned vs. the result of that reference invocation.

    Specifically:

    let f = Func<...>
    return f; vs. return f(...);
    

    Due to some reason .Net designers chose Expression.Quote(f) for the first case and plain f for the second. To my view this causes a great deal of confusion, since in most programming languages returning a value is direct (no need for Quote or any other operation), but invocation does require extra writing (parentheses + arguments), which translates to some kind of invoke at MSIL level. .Net designers made it the opposite for the expression trees. Would be interesting to know the reason.

提交回复
热议问题