NET問答: 是否有通用的方法判斷一個 Type 是 Number ?

咨詢區(qū)
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;
}
}
回答區(qū)
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 類型的話,也可以排除掉。
點評區(qū)
這套題還是挺有意思的,Konamiman 大佬提供的方法簡潔高效,也并沒有使用反射,而是直接調(diào)取它的 類型句柄 直接判斷,學習了!
【推薦】.NET Core開發(fā)實戰(zhàn)視頻課程 ★★★
.NET Core實戰(zhàn)項目之CMS 第一章 入門篇-開篇及總體規(guī)劃
【.NET Core微服務實戰(zhàn)-統(tǒng)一身份認證】開篇及目錄索引
Redis基本使用及百億數(shù)據(jù)量中的使用技巧分享(附視頻地址及觀看指南)
.NET Core中的一個接口多種實現(xiàn)的依賴注入與動態(tài)選擇看這篇就夠了
用abp vNext快速開發(fā)Quartz.NET定時任務管理界面
在ASP.NET Core中創(chuàng)建基于Quartz.NET托管服務輕松實現(xiàn)作業(yè)調(diào)度
評論
圖片
表情
