C# - how to determine whether a Type is a number

后端 未结 18 2306
傲寒
傲寒 2020-11-28 22:47

Is there a way to determine whether or not a given .Net Type is a number? For example: System.UInt32/UInt16/Double are all numbers. I want to avoid a long switc

18条回答
  •  猫巷女王i
    2020-11-28 23:30

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

    Note about optimization removed (see enzi comments) And if you really want to optimize it (losing readability and some safety...):

    public static bool IsNumericType(Type type)
    {
      TypeCode typeCode = Type.GetTypeCode(type);
      //The TypeCode of numerical types are between SByte (5) and Decimal (15).
      return (int)typeCode >= 5 && (int)typeCode <= 15;
    }
    

提交回复
热议问题