C# Convert.ToInt32 和 Int32.Parse 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15894963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:19:14  来源:igfitidea点击:

What's the difference between Convert.ToInt32 and Int32.Parse?

c#

提问by th1rdey3

In C#there you can convert a string to Int32 using both Int32.Parseand Convert.ToInt32. What's the difference between them? Which performs better? What are the scenarios where I should use Convert.ToInt32over Int32.Parseand vice-versa?

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

回答by ronen

Basically Convert.ToInt32uses 'Int32.Parse' behind scenes but at the bottom line Convert.ToInt32A nullwill return 0. while in Int32.Parsean Exception will be raised.

基本上Convert.ToInt32在幕后使用 'Int32.Parse' 但在底线 Convert.ToInt32Anull将返回 0。而在Int32.ParseException 中将引发。

回答by jlvaquero

Convert.ToInt32 (string value)

Convert.ToInt32(字符串值)

From MSDN:

来自 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.Parsemethod on value.

返回与 value 的值等效的 32 位有符号整数。- 或 - 如果 value 是空引用,则为零(在 Visual Basic 中为 Nothing)。返回值是Int32.Parse对值调用方法的结果。

回答by Sachin

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.

Int32.Parse (string s) 方法将数字的字符串表示形式转换为其等效的 32 位有符号整数。当 s 为空引用时,它将抛出 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.

Convert.ToInt32(string s) 方法转换指定的 32 位有符号整数等效字符串表示形式。这样依次调用Int32.Parse()方法。当 s 为空引用时,它将返回 0 而不是抛出 ArgumentNullException。

回答by Tigran

If you look with Reflectoror ILSpyinto the mscorlibyou will see the following code for Convert.ToInt32

如果你看看与反射器ILSpymscorlib你会看到下面的代码Convert.ToInt32

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

So, internally it uses the int.Parsebut with the CurrentCulture. And actually from the code is understandable why when I specify nulllike a parameter this method does not throw an exception.

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