What's the main difference between int.Parse() and Convert.ToInt32

前端 未结 13 2296
-上瘾入骨i
-上瘾入骨i 2020-11-22 08:47
  • What is the main difference between int.Parse() and Convert.ToInt32()?
  • Which one is to be preferred
13条回答
  •  梦如初夏
    2020-11-22 09:04

    Have a look in reflector:

    int.Parse("32"):

    public static int Parse(string s)
    {
        return System.Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
    }
    

    which is a call to:

    internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
    {
        byte* stackBuffer = stackalloc byte[1 * 0x72];
        NumberBuffer number = new NumberBuffer(stackBuffer);
        int num = 0;
        StringToNumber(s, style, ref number, info, false);
        if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
        {
            if (!HexNumberToInt32(ref number, ref num))
            {
                throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
            }
            return num;
        }
        if (!NumberToInt32(ref number, ref num))
        {
            throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
        }
        return num;
    }
    

    Convert.ToInt32("32"):

    public static int ToInt32(string value)
    {
        if (value == null)
        {
            return 0;
        }
        return int.Parse(value, CultureInfo.CurrentCulture);
    }
    

    As the first (Dave M's) comment says.

提交回复
热议问题