C# - 型が数値かどうかを判断する方法 質問する

C# - 型が数値かどうかを判断する方法 質問する

特定の .Net タイプが数値かどうかを判断する方法はありますか? たとえば、System.UInt32/UInt16/Doubleはすべて数値です。 での長い switch-case を避けたいですType.FullName

ベストアンサー1

これを試して:

Type type = object.GetType();
bool isNumber = (type.IsPrimitiveImple && type != typeof(bool) && type != typeof(char));

プリミティブ型は、Boolean、Byte、SByte、Int16、UInt16、Int32、UInt32、Int64、UInt64、Char、Double、Single です。

撮影ギヨームの解決策もう少し先へ:

public static bool IsNumericType(this object o)
{   
  switch (Type.GetTypeCode(o.GetType()))
  {
    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;
  }
}

使用法:

int i = 32;
i.IsNumericType(); // True

string s = "Hello World";
s.IsNumericType(); // False

おすすめ記事