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

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

    You could use Type.IsPrimitive and then sort out the Boolean and Char types, something like this:

    bool IsNumeric(Type type)
    {
        return type.IsPrimitive && type!=typeof(char) && type!=typeof(bool);
    }
    

    EDIT: You may want to exclude the IntPtr and UIntPtr types as well, if you don't consider them to be numeric.

提交回复
热议问题