Is there a try Convert.ToInt32… avoiding exceptions

前端 未结 7 1908
长发绾君心
长发绾君心 2020-12-08 18:51

I\'d like to know if there is a \"safe\" way to convert an object to an int, avoiding exceptions.

I\'m looking for something like public static bo

7条回答
  •  醉话见心
    2020-12-08 19:06

    I would use a mixture of what you are already doing;

    • Check if the object is null - return false and the value 0;
    • Attempt to convert directly - if successful, return true and the converted value
    • Attempt to parse value.ToString() - if successfull, return true and the parsed value
    • Any other case - Return false and the value 0, as object is not convertible/parsible

    The resulting code:

    public static bool TryToInt32(object value, out int result)
    {
        result = 0;
        if (value == null)
        {
            return false;
        }
    
        //Try to convert directly
        try
        {
            result = Convert.ToInt32(value);
            return true;
        }
        catch
        {
            //Could not convert, moving on
        }
    
        //Try to parse string-representation
        if (Int32.TryParse(value.ToString(), out result))
        {
            return true;
        }
    
        //If parsing also failed, object cannot be converted or paresed
        return false;
    }
    

提交回复
热议问题