2012-01-12 17 views
9

cuál es la forma más fácil de comprobar si un typeof() es matemáticamente utilizable (numérico).typeof() para comprobar los valores numéricos

¿Es necesario utilizar el TryParse method o compruebe el presente:

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; 
    } 

si hay una manera más fácil de lograr esto, su libertad de sugerir

+0

Relacionados: http://stackoverflow.com/questions/828807/what-is-the-base-class-for-c-sharp-numeric-value-types –

+0

¿Qué significa "matemáticamente utilizable"? ¿Es una matriz de dobles matemáticamente utilizable, por ejemplo? Creo que es. –

+3

posible duplicado de [Usando .Net, ¿cómo puedo determinar si un tipo es un ValueType numérico?] (Http://stackoverflow.com/questions/124411/using-net-how-can-i-determine-if-a -type-is-a-numeric-valuetype) –

Respuesta

10

No hay mucho que ver, por desgracia . Pero a partir de C# 3 en adelante, se puede hacer algo más elaborado:

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) 
       ); 
    } 
} 

lo que el código original se puede escribir así:

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

estos son todos los tipos numéricos conocidos? (excepto char) de hay más? – Moonlight

+0

No, este es un subconjunto. Para obtener una lista completa, consulte [esta respuesta] (http://stackoverflow.com/a/5182747/126052) de otro tema. Puedo actualizar mi respuesta más tarde. – Humberto

+0

lo he editado por usted, agregué algunos tipos numéricos adicionales – Moonlight

3

Puede comprobar las interfaces que implementan los tipos numéricos:

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

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