C# - 如何确定类型是否为数字

标签 c# .net types

有没有办法确定给定的 .Net 类型是否为数字?例如:System.UInt32/UInt16/Double都是数字。我想避免在 Type.FullName 上使用较长的 switch-case。

最佳答案

试试这个:

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

The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Char, Double,and Single.

服用 Guillaume's solution更进一步:

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

关于C# - 如何确定类型是否为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1749966/

相关文章:

mysql - 如何在Mysql中选择varchar大小?

swift - 以编程方式访问 UIViewController 子类中 UIView 子类的成员

c# - NHibernate SaveOrUpdate 子集合未使用标识 ID 更新

.net - 基于公共(public)接口(interface)的Windsor组件注册

c# - 如何自动创建 WPF Viewmodel 属性

C# .Net SqlConnection 到 LocalDB

c# - 如何在 scriptcs csx 脚本中定义扩展方法

nhibernate - 使用 Fluent NHibernate 进行继承映射

c# - 将 block 与线程一起使用

C# COM DLL 阻止 VBA 应用程序退出