2017-03-08 79 views
0

我有一個覆蓋Unary Visitor似乎工作正常,但我需要從節點獲取操作數的值。自定義表達式樹訪問者 - 如何獲取UnaryExpression節點的值?

如果它是一個常量表達式,這是很容易實現:

var value = ((ConstantExpression) node.Operand).Value; 

的問題是如何實現這一目標,如果節點是值類型像一個int MemberExpression:

protected override Expression VisitUnary(UnaryExpression node) 
{     
    //get the value stored in the node.Operand  
} 

回答

0

不能保證UnaryExpression連接到一個恆定值...在x => (int)x例如(int)是一個UnaryExpression未連接到一個常數值。

但是......你可以檢查它是否是...

// Unravel (object)(long)5 
while (node.Operand is UnaryExpression) 
{ 
    node = (UnaryExpression)node.Operand; 
} 

ConstantExpression ce = node.Operand as ConstantExpression; 

if (ce != null) 
{ 
    // success! 
    object value = ce.Value; 
}