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
What's the difference between Convert.ToInt32 and Int32.Parse?
提问by th1rdey3
In C#
there you can convert a string to Int32 using both Int32.Parse
and Convert.ToInt32
. What's the difference between them? Which performs better? What are the scenarios where I should use Convert.ToInt32
over Int32.Parse
and vice-versa?
在C#
那里,您可以使用Int32.Parse
和将字符串转换为 Int32 Convert.ToInt32
。它们之间有什么区别?哪个表现更好?我应该在哪些情况下使用Convert.ToInt32
,Int32.Parse
反之亦然?
回答by ronen
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.
基本上Convert.ToInt32
在幕后使用 'Int32.Parse' 但在底线
Convert.ToInt32
Anull
将返回 0。而在Int32.Parse
Exception 中将引发。
回答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.Parse
method 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 mscorlib
you will see the following code for Convert.ToInt32
如果你看看与反射器或ILSpy到mscorlib
你会看到下面的代码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 null
like a parameter this method does not throw an exception.
因此,它在内部使用int.Parse但使用CurrentCulture
. 实际上从代码中可以理解为什么当我null
像参数一样指定此方法时不会引发异常。