2012-01-12 39 views
9

檢查typeof()是否在數學上可用(數字)的最簡單方法是什麼?typeof()檢查數字值

做我需要使用TryParse method或通過此檢查:

if (!(DC.DataType == typeof(int) || DC.DataType == typeof(double) || DC.DataType == typeof(long) || DC.DataType == typeof(short) || DC.DataType == typeof(float))) 
    { 
      MessageBox.Show("Non decimal data cant be calculated"); 
      return; 
    } 

,如果有一個更簡單的方法來做到這一點,你可以自由地提出

+0

相關:http://stackoverflow.com/questions/828807/what-is-the-base-class-for-c-sharp-numeric-value-types – 2012-01-12 13:39:44

+0

「數學上可用」是什麼意思?對於例子來說,雙數組是數學上可用的嗎?我覺得是這樣的。 – 2012-01-12 13:39:53

+3

[使用.Net,我怎樣才能確定一個類型是否是一個Numeric ValueType?](http://stackoverflow.com/questions/124411/using-net-how-can-i-determine-if-a -type-is-a-numeric-valueetype) – 2012-01-12 13:40:34

回答

10

沒有什麼太大的事,很遺憾。但是從C#3起,你可以做一些票友:

public static class NumericTypeExtension 
{ 
    public static bool IsNumeric(this Type dataType) 
    { 
     if (dataType == null) 
      throw new ArgumentNullException("dataType"); 

     return (dataType == typeof(int) 
       || dataType == typeof(double) 
       || dataType == typeof(long) 
       || dataType == typeof(short) 
       || dataType == typeof(float) 
       || dataType == typeof(Int16) 
       || dataType == typeof(Int32) 
       || dataType == typeof(Int64) 
       || dataType == typeof(uint) 
       || dataType == typeof(UInt16) 
       || dataType == typeof(UInt32) 
       || dataType == typeof(UInt64) 
       || dataType == typeof(sbyte) 
       || dataType == typeof(Single) 
       ); 
    } 
} 

所以你的原始代碼可以這樣寫:

if (!DC.DataType.IsNumeric()) 
{ 
     MessageBox.Show("Non decimal data cant be calculated"); 
     return; 
} 
+0

這些都是已知的數字類型? (除了char)還有更多嗎? – Moonlight 2012-01-12 13:57:51

+0

不,這是一個子集。有關完整列表,請參閱另一主題的[此答案](http://stackoverflow.com/a/5182747/126052)。我稍後可能會更新我的答案。 – Humberto 2012-01-12 14:03:45

+0

我爲你編輯它,增加了一些額外的數字類型 – Moonlight 2012-01-12 14:34:19

3

您可以檢查該數值類型實現的接口:

if (data is IConvertible) { 
    double value = ((IConvertible)data).ToDouble(); 
    // do calculations 
} 

if (data is IComparable) { 
    if (((IComparable)data).CompareTo(42) < 0) { 
    // less than 42 
    } 
}