有没有办法确定给定的 .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/