Is there a try Convert.ToInt32… avoiding exceptions

前端 未结 7 1906
长发绾君心
长发绾君心 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:13

    This version using a type converter would only convert to string as a last resort but also not throw an exception:

    public static bool TryToInt32(object value, out int result)
    {
        if (value == null)
        {
            result = 0;
            return false;
        }
        var typeConverter =  System.ComponentModel.TypeDescriptor.GetConverter(value);
        if (typeConverter != null && typeConverter.CanConvertTo(typeof(int)))
        {
            var convertTo = typeConverter.ConvertTo(value, typeof(int));
            if (convertTo != null)
            {
                result = (int)convertTo;
                return true;
            }
        }
        return int.TryParse(value.ToString(), out result);
    }
    

提交回复
热议问题