我有以下資料結構:
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 的運算式?
uj5u.com熱心網友回復:
您不能遍歷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
}
如果您使用塊體屬性,將生成相同的代碼。正如你所看到的,Expression任何地方都沒有。你可以在 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://www.uj5u.com/gongcheng/332939.html
