网站排名提高,学做名片的网站,windows优化大师兑换码,建站网站破解版咨询区 Adi Barda#xff1a;请问是否有一种方式可以判断 .NET Type 是一个 number#xff0c;这里的number不单单是 int #xff0c;还有可能是 System.UInt32/UInt16/Double 等等#xff0c;我真的不想写那种长长的 switch case 来摆平这个问题。比如下面的代码#xff… 咨询区 Adi Barda请问是否有一种方式可以判断 .NET Type 是一个 number这里的number不单单是 int 还有可能是 System.UInt32/UInt16/Double 等等我真的不想写那种长长的 switch case 来摆平这个问题。比如下面的代码
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;}
}回答区 Jon Skeet如果你不想使用 switch可以用 HashSet 或者 Dictionary 来替代参考如下代码:
public static class TypeHelper
{private static readonly HashSetType NumericTypes new HashSetType{typeof(int), typeof(double), typeof(decimal),typeof(long), typeof(short), typeof(sbyte),typeof(byte), typeof(ulong), typeof(ushort), typeof(uint), typeof(float)};public static bool IsNumeric(Type myType){return NumericTypes.Contains(Nullable.GetUnderlyingType(myType) ?? myType);}
}当 .NET 有新的类型加入时你也可以非常方便的将其加入到 NumericTypes 中比如BigInteger 和 Complex。Konamiman你可以使用 Type.IsPrimitive 并排除掉 Boolean 和 Char 类型比如下面这样的简单粗暴
bool IsNumeric(Type type)
{return type.IsPrimitive type!typeof(char) type!typeof(bool);
}如果你不认为 IntPtr,UintPtr 是 numeric 类型的话也可以排除掉。点评区 这套题还是挺有意思的Konamiman 大佬提供的方法简洁高效也并没有使用反射而是直接调取它的 类型句柄 直接判断学习了