首页 文章详情

NET问答: 是否有通用的方法判断一个 Type 是 Number ?

DotNetCore实战 | 295 2021-06-16 10:07 0 0 0
UniSMS (合一短信)


咨询区

  • 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开发实战视频课程 ★★★

.NET Core实战项目之CMS 第一章 入门篇-开篇及总体规划

【.NET Core微服务实战-统一身份认证】开篇及目录索引

Redis基本使用及百亿数据量中的使用技巧分享(附视频地址及观看指南)

.NET Core中的一个接口多种实现的依赖注入与动态选择看这篇就够了

10个小技巧助您写出高性能的ASP.NET Core代码

用abp vNext快速开发Quartz.NET定时任务管理界面

在ASP.NET Core中创建基于Quartz.NET托管服务轻松实现作业调度

现身说法:实际业务出发分析百亿数据量下的多表查询优化

关于C#异步编程你应该了解的几点建议

C#异步编程看这篇就够了


good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter