C# - how to determine whether a Type is a number

后端 未结 18 2305
傲寒
傲寒 2020-11-28 22:47

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 switc

18条回答
  •  我在风中等你
    2020-11-28 23:49

    None of the solutions takes Nullable into account.

    I modified Jon Skeet's solution a bit:

        private static HashSet NumericTypes = new HashSet
        {
            typeof(int),
            typeof(uint),
            typeof(double),
            typeof(decimal),
            ...
        };
    
        internal static bool IsNumericType(Type type)
        {
            return NumericTypes.Contains(type) ||
                   NumericTypes.Contains(Nullable.GetUnderlyingType(type));
        }
    

    I know I could just add the nullables itself to my HashSet. But this solution avoid the danger of forgetting to add a specific Nullable to your list.

        private static HashSet NumericTypes = new HashSet
        {
            typeof(int),
            typeof(int?),
            ...
        };
    

提交回复
热议问题