Checking if an object is a number in C#

前端 未结 11 1583
粉色の甜心
粉色の甜心 2020-11-29 19:35

I\'d like to check if an object is a number so that .ToString() would result in a string containing digits and +,-,.

11条回答
  •  鱼传尺愫
    2020-11-29 20:07

    Take advantage of the IsPrimitive property to make a handy extension method:

    public static bool IsNumber(this object obj)
    {
        if (Equals(obj, null))
        {
            return false;
        }
    
        Type objType = obj.GetType();
        objType = Nullable.GetUnderlyingType(objType) ?? objType;
    
        if (objType.IsPrimitive)
        {
            return objType != typeof(bool) && 
                objType != typeof(char) && 
                objType != typeof(IntPtr) && 
                objType != typeof(UIntPtr);
        }
    
        return objType == typeof(decimal);
    }
    

    EDIT: Fixed as per comments. The generics were removed since .GetType() boxes value types. Also included fix for nullable values.

提交回复
热议问题