11

在那里,您可以使用和C#将字符串转换为 Int32 。他们之间有什么区别?哪个表现更好?我应该在哪些情况下使用over ,反之亦然?Int32.ParseConvert.ToInt32Convert.ToInt32Int32.Parse

4

4 回答 4

17

如果您使用ReflectorILSpy查看您将mscorlib看到以下代码Convert.ToInt32

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

因此,在内部它使用int.Parse但与CurrentCulture. 实际上从代码中可以理解为什么当我null像参数一样指定此方法时不会引发异常。

于 2013-04-09T06:46:58.567 回答
7

Basically Convert.ToInt32 uses 'Int32.Parse' behind scenes but at the bottom line Convert.ToInt32 A null will return 0. while in Int32.Parse an Exception will be raised.

于 2013-04-09T06:42:09.407 回答
3

Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent. When s is a null reference, it will throw ArgumentNullException.

whereas

Convert.ToInt32(string s) method converts the specified string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method. When s is a null reference, it will return 0 rather than throw ArgumentNullException.

于 2013-04-09T06:42:59.080 回答
2

Convert.ToInt32 (string value)

From MSDN:

Returns a 32-bit signed integer equivalent to the value of value. -or- Zero if value is a null reference (Nothing in Visual Basic). The return value is the result of invoking the Int32.Parse method on value.

于 2013-04-09T06:42:25.173 回答