Int32.Parse() VS Convert.ToInt32()?

前端 未结 3 1262
轮回少年
轮回少年 2021-01-01 10:59
intID1 = Int32.Parse(myValue.ToString());
intID2 = Convert.ToInt32(myValue);

Which one is better and why?

相关标签:
3条回答
  • 2021-01-01 11:42

    They are exactly the same, except that Convert.ToInt32(null) returns 0.

    Convert.ToInt32 is defined as follows:

        public static int ToInt32(String value) {
            if (value == null) 
                return 0;
            return Int32.Parse(value, CultureInfo.CurrentCulture);
        }
    
    0 讨论(0)
  • 2021-01-01 11:42

    It depends on what you mean by "better" because "better" is subjective.

    For instance - code readability. Some people prefer to see "Convert" in their code; others prefer to see "Parse".

    In terms of speed, they're also both roughly equal according to these benchmarks.

    Or do you always wants a value returned? As others have mentioned, ConvertTo returns a 0 (zero) for null values whereas you don't get that option with Parse.

    0 讨论(0)
  • 2021-01-01 11:55

    Well, Reflector says...

    public static int ToInt32(string value)
    {
        if (value == null)
        {
            return 0;
        }
        return int.Parse(value, CultureInfo.CurrentCulture);
    }
    
    public static int Parse(string s)
    {
        return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
    }
    

    So they're basically the same except that Convert.ToInt32() does an added null check.

    0 讨论(0)
提交回复
热议问题