2013-10-28 66 views
0

我有以下表達式有什麼辦法來檢查包含數字的ConstantExpression是否爲負數?

int someNumber = somevalue; 
ConstantExpression expr = Expression.Constant(someNumber); 

有沒有一種方法來檢查,看看是否EXPR < 0或expr是負數?

+0

你想建立:在第二個例子中使用

ConstantExpression expr = /* ... */; if (expr.Value != null && expr.Value.GetType().IsNumericType()) { // Perform an appropriate comparison _somehow_, but not necessarily like this // (using Convert makes my skin crawl). var decimalValue = Convert.ToDecimal(expr.Value); if (decimalValue < 0m) { /* do something */ } } 

擴展方法執行此比較的_expression_,還是隻想直接在C#代碼中分析常量值? –

+0

我想分析一下這個ConstantExpression裏面是否有數字值(比如decimal,int或者double),看看這個值是否定的。 – fahadash

+0

是的,但是你想直接在你的C#代碼中做這個分析嗎,還是你想編寫一個執行這個邏輯的表達式樹? –

回答

2

如果你知道常量的類型,你可以簡單地投和分析的基本恆定值。

ConstantExpression expr = /* ... */; 
var intConstant = expr.Value as int?; 
if (intConstant < 0) { /* do something */ } 

當然,如果你所有的是一個Expression,你需要檢查它以確定它是否一個ConstantExpression

如果你不知道的類型,但要檢查任何有效的數值類型:

public static Type GetNonNullableType([NotNull] this Type type) 
{ 
    if (type == null) 
     throw new ArgumentNullException("type"); 

    if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Nullable<>)) 
     return type; 

    return type.GetGenericArguments()[0]; 
} 

public static bool IsNumericType(this Type type) 
{ 
    if (type == null) 
     throw new ArgumentNullException("type"); 

    type = type.GetNonNullableType(); 

    if (type.IsEnum) 
     return false; 

    switch (Type.GetTypeCode(type)) 
    { 
     case TypeCode.SByte: 
     case TypeCode.Byte: 
     case TypeCode.Int16: 
     case TypeCode.UInt16: 
     case TypeCode.Int32: 
     case TypeCode.UInt32: 
     case TypeCode.Int64: 
     case TypeCode.UInt64: 
     case TypeCode.Single: 
     case TypeCode.Double: 
     case TypeCode.Decimal: 
      return true; 
    } 

    return false; 
} 
+1

我不會在這種情況下使用'as'。如果該值具有不同的類型,則希望立即得到明確的異常。 – svick

+2

我對OP認爲是理想行爲還是有效輸入不做任何假設。他問如何分離負數;他沒有說任何關於數值的所有值。我把它留給他,以最好地決定如何檢查和處理意想不到的價值。 –

相關問題