咨询区
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 HashSet<Type> NumericTypes = new HashSet<Type>
{
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
大佬提供的方法简洁高效,也并没有使用反射,而是直接调取它的 类型句柄
直接判断,学习了!
.NET Core实战项目之CMS 第一章 入门篇-开篇及总体规划
【.NET Core微服务实战-统一身份认证】开篇及目录索引
Redis基本使用及百亿数据量中的使用技巧分享(附视频地址及观看指南)
.NET Core中的一个接口多种实现的依赖注入与动态选择看这篇就够了
用abp vNext快速开发Quartz.NET定时任务管理界面