Is there a try Convert.ToInt32… avoiding exceptions

前端 未结 7 1771
长发绾君心
长发绾君心 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:04
    int variable = 0;
    int.TryParse(stringValue, out variable);
    

    If it can't be parsed, the variable will be 0. See http://msdn.microsoft.com/en-us/library/f02979c7.aspx

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-08 19:07

    I wrote this mess, looking at it makes me sad.

    using System;
    using System.Globalization;
    
    internal static class ObjectExt
    {
        internal static bool TryConvertToDouble(object value, out double result)
        {
            if (value == null || value is bool)
            {
                result = 0;
                return false;
            }
    
            if (value is double)
            {
                result = (double)value;
                return true;
            }
    
            var text = value as string;
            if (text != null)
            {
                return double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out result);
            }
    
            var convertible = value as IConvertible;
            if (convertible == null)
            {
                result = 0;
                return false;
            }
    
            try
            {
                result = convertible.ToDouble(CultureInfo.InvariantCulture);
                return true;
            }
            catch (Exception)
            {
                result = 0;
                return false;
            }
        }
    }
    

    Edit Notice now I answered for double when the question was int, keeping it any way. Maybe useful for someone.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-12-08 19:14

    No need to re-invent the wheel here. use int.TryParse to achieve your goal. It returns a bool to show that value is parsed or not. and if parsed the result is saved in the output variable.

    int result;
    object a = 5;
    if(int.TryParse(a.ToString(),out result))
    {
       Console.WriteLine("value is parsed");  //will print 5
    }    
    
    object b = a5;
    if(int.TryParse(b.ToString(),out result))
    {
        Console.WriteLine("value is parsed");  
    }
    else
    {
        Console.WriteLine("input is not a valid integer");  //will print this   
    }
    
    0 讨论(0)
  • 2020-12-08 19:16

    Return a nullable int. that way you know whether you parsed 0.

    int? value = int.TryParse(stringValue, out int outValue) 
        ? outValue
        : default(int?);
    
    0 讨论(0)
提交回复
热议问题