我有以下数据结构:
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的表达式?
发布于 2021-10-23 09:23:59
不能遍历表达式体属性的Expression,因为它们不是Expression对象。表达式主体属性与其他属性没有什么不同,只是它们的语法不同。您在此处的财产:
public decimal LinePrice {
get => Quantity * LinePrice; // did you mean UnitPrice?
}编译成:(就像在SharpLab上看到的那样)
.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
// 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);https://stackoverflow.com/questions/69686569
复制相似问题