- C#,如何确定类型是否是一个数字 [英] C# - how to determine whether a Type is a number
问题描述
有没有一种方法来确定一个给定的.NET类型是否是一个数字?例如: System.UInt32 / UINT16 /双人间
都是数字。我想避免在长开关的情况下 Type.FullName
。
<击>试试这个:
键入类型= object.GetType();
布尔ISNUMBER =(type.IsPrimitiveImple&安培;&放大器;类型= typeof运算(布尔)及!&放大器;类型= typeof运算(char)的!);
的基本类型有布尔,字节,
为SByte,Int16的,UINT16,的Int32,UInt32的,
Int64的,UINT64,煤焦,Double和
单。
罢工>
块引用>拍摄<一个href=\"http://stackoverflow.com/questions/1749966/c-how-to-determine-whether-a-type-is-a-number/1750093#1750093\">Guillaume's解决方案的远一点:
公共静态布尔IsNumericType(该对象o)
{
开关(Type.GetType code(o.GetType()))
{
案件类型code.Byte:
案件类型code.SByte:
案件类型code.UInt16:
案件类型code.UInt32:
案件类型code.UInt64:
案件类型code.Int16:
案件类型code.Int32:
案件类型code.Int64:
案件类型code.Decimal:
案件类型code.Double:
案件类型code.Single:
返回true;
默认:
返回false;
}
}用法:
INT I = 32;
i.IsNumericType(); //真字符串s =Hello World的;
s.IsNumericType(); //假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 switch-case on theType.FullName
.解决方案
Try this: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.
Taking Guillaume's solution a little further:
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; } }
Usage:
int i = 32; i.IsNumericType(); // True string s = "Hello World"; s.IsNumericType(); // False
这篇关于 - C#,如何确定类型是否是一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!