typeof() to check for Numeric values

限于喜欢 提交于 2019-12-10 12:54:01

问题


what is the easiest way to check if a typeof() is mathematically usable(numeric).

do i need to use the TryParse method or check it by this:

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

if there is a more easy way to achieve this, your free to suggest


回答1:


There's nothing much to do, unfortunately. But from C# 3 onwards, you can do something fancier:

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

so your original code can be written like this:

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



回答2:


You can check for the interfaces that the numeric types implement:

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

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


来源:https://stackoverflow.com/questions/8835982/typeof-to-check-for-numeric-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!