C# - 如何确定类型是否为数字 [英] C# - how to determine whether a Type is a number
本文介绍了C# - 如何确定类型是否为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法确定给定的 .Net 类型是否为数字?例如:System.UInt32/UInt16/Double
都是数字.我想避免 Type.FullName
上的长切换案例.
解决方案
试试这个:
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 和单身的.罢工>
采用 Guillaume 的解决方案 再远一点:
public static bool IsNumericType(this object o){开关 (Type.GetTypeCode(o.GetType())){案例类型代码.字节:案例类型代码.SByte:案例类型代码.UInt16:案例类型代码.UInt32:案例类型代码.UInt64:案例类型代码.Int16:案例类型代码.Int32:案例 TypeCode.Int64:案例类型代码.十进制:案例 TypeCode.Double:案例 TypeCode.Single:返回真;默认:返回假;}}
用法:
int i = 32;i.IsNumericType();//真的string 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 the Type.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屋!
查看全文