首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否可以使用ExpressionVisitor遍历表达式体成员?

是否可以使用ExpressionVisitor遍历表达式体成员?
EN

Stack Overflow用户
提问于 2021-10-23 08:54:30
回答 1查看 21关注 0票数 0

我有以下数据结构:

代码语言:javascript
复制
class OrderLine : Table
{
    public int Id { get; set; }

    public Order Order { get; set; }

    public decimal Quantity { get; set; }

    public decimal UnitPrice { get; set; }

    [CalculatedField]
    public decimal LinePrice {
        get => Quantity * LinePrice;
    }
}

我想用ExpressionVisitor遍历LinePrice getter的表达式。构建对远程系统的请求。

有没有办法(通过反射?)来访问表达式主体成员getter的表达式?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-23 09:23:59

不能遍历表达式体属性的Expression,因为它们不是Expression对象。表达式主体属性与其他属性没有什么不同,只是它们的语法不同。您在此处的财产:

代码语言:javascript
复制
public decimal LinePrice {
    get => Quantity * LinePrice; // did you mean UnitPrice?
}

编译成:(就像在SharpLab上看到的那样)

代码语言:javascript
复制
.method public hidebysig specialname 
    instance valuetype [System.Private.CoreLib]System.Decimal get_LinePrice () cil managed 
{
    .maxstack 8

    IL_0000: ldarg.0
    IL_0001: call instance valuetype [System.Private.CoreLib]System.Decimal OrderLine::get_Quantity()
    IL_0006: ldarg.0
    IL_0007: call instance valuetype [System.Private.CoreLib]System.Decimal OrderLine::get_LinePrice()
    IL_000c: call valuetype [System.Private.CoreLib]System.Decimal [System.Private.CoreLib]System.Decimal::op_Multiply(valuetype [System.Private.CoreLib]System.Decimal, valuetype [System.Private.CoreLib]System.Decimal)
    IL_0011: ret
}

这与使用块体属性时生成的代码相同。如你所见,任何地方都没有Expressions。您可以在SharpLab上尝试此功能。这表明表达式主体成员是纯粹的语法糖。

如果您希望将其作为Expression进行遍历,则实际上应该声明一个Expression

代码语言:javascript
复制
// now you can traverse this with ExpressionVisitor
public static readonly Expression<Func<OrderLine, decimal>> LinePriceExpression 
    = x => x.Quantity * x.UnitPrice;

// to avoid repeating "Quantity * UnitPrice" again in the property getter,
// you can compile the expression and reuse it
private static readonly Func<OrderLine, decimal> LinePriceExpressionCompiled 
    = LinePriceExpression.Compile();

public decimal LinePrice => LinePriceExpressionCompiled(this);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69686569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档