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

后端 未结 18 2307
傲寒
傲寒 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:37

    Switch is a little slow, bacause every time methods in the worst situation will be go through all type. I think, using Dictonary is more nice, in this situation you will be have O(1):

    public static class TypeExtensions
    {
        private static readonly HashSet NumberTypes = new HashSet();
    
        static TypeExtensions()
        {
            NumberTypes.Add(typeof(byte));
            NumberTypes.Add(typeof(decimal));
            NumberTypes.Add(typeof(double));
            NumberTypes.Add(typeof(float));
            NumberTypes.Add(typeof(int));
            NumberTypes.Add(typeof(long));
            NumberTypes.Add(typeof(sbyte));
            NumberTypes.Add(typeof(short));
            NumberTypes.Add(typeof(uint));
            NumberTypes.Add(typeof(ulong));
            NumberTypes.Add(typeof(ushort));
        }
    
        public static bool IsNumber(this Type type)
        {
            return NumberTypes.Contains(type);
        }
    }
    

提交回复
热议问题