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

后端 未结 18 2303
傲寒
傲寒 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 23:40

    Don't use a switch - just use a set:

    HashSet NumericTypes = new HashSet
    {
        typeof(decimal), typeof(byte), typeof(sbyte),
        typeof(short), typeof(ushort), ...
    };
    

    EDIT: One advantage of this over using a type code is that when new numeric types are introduced into .NET (e.g. BigInteger and Complex) it's easy to adjust - whereas those types won't get a type code.

提交回复
热议问题