.Net判断一个对象是否为数值类型

时间:2023-03-08 21:28:46

这乍一听是个很简单的事,但突然搞起来还真有点无从下手的感觉。

首先当然是通过GetType()方法反射获取其类型信息,然后对其进行分析,但是类型信息Type中并没有简单地给出这么一个属性进行判断。

老外给出的方法是:

public static bool IsNumeric(this Type dataType)
{
if (dataType == null)
throw new ArgumentNullException("dataType"); return (dataType == typeof(int)
|| dataType == typeof(double)
|| dataType == typeof(long)
|| dataType == typeof(short)
|| dataType == typeof(float)
|| dataType == typeof(Int16)
|| dataType == typeof(Int32)
|| dataType == typeof(Int64)
|| dataType == typeof(uint)
|| dataType == typeof(UInt16)
|| dataType == typeof(UInt32)
|| dataType == typeof(UInt64)
|| dataType == typeof(sbyte)
|| dataType == typeof(Single)
);
}

我勒个去。。。他是想穷举比对所有已知数值类型。。。。这么做应该是可以,就是性能差点并且不雅吧。

而且~他好像还忘了Decimal。。。

我研究了一下这些数值类型,它们貌似都是结构而非类,而且都有共同的接口:

IFormattable, IComparable, IConvertible

其中IFormattable接口是数值类型有别于其它几个基础类型的接口。

这样就非常好办了,代码如下:

public static bool IsNumericType(this Type o)
{
return !o.IsClass && !o.IsInterface && o.GetInterfaces().Any(q => q == typeof(IFormattable));
}

另外除了基本类型之外还有可空类型Nullable<T>,就是常用的例如double?这种,对于泛型的类型的匹配我不知该怎么做才好,赶时间就没深究,用了个偷懒的方法实现了:

public static bool IsNullableNumericType(this Type o)
{
if (!o.Name.StartsWith("Nullable")) return false;
return o.GetGenericArguments()[].IsNumericType();
}

看吧,只是判断一下类型名称是不是以“Nullable”开始,如果是的话再对其第一个泛型参数类型进行上面的判断,这样肯定不是100%靠谱的,希望有识之士能够完善一下这个方法并分享出来哈。