C# int.Parse() 和 Convert.ToInt32 之间的主要区别是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/199470/
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 main difference between int.Parse() and Convert.ToInt32
提问by jbcedge
- What is the main difference between
int.Parse()
andConvert.ToInt32()
? - Which one is to be preferred
int.Parse()
和之间的主要区别是Convert.ToInt32()
什么?- 哪个是首选
采纳答案by Dave Markle
If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use
Int32.Parse()
.If you're collecting input from a user, you'd generally use
Int32.TryParse()
, since it allows you more fine-grained control over the situation when the user enters invalid input.Convert.ToInt32()
takes an object as its argument. (See Chris S's answer for how it works)Convert.ToInt32()
also does not throwArgumentNullException
when its argument is null the wayInt32.Parse()
does. That also means thatConvert.ToInt32()
is probably a wee bit slower thanInt32.Parse()
, though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.
如果您有一个字符串,并且您希望它始终是一个整数(例如,如果某个 Web 服务以字符串格式向您发送一个整数),您可以使用
Int32.Parse()
.如果您正在收集用户的输入,您通常会使用
Int32.TryParse()
,因为当用户输入无效输入时,它允许您对情况进行更细粒度的控制。Convert.ToInt32()
将一个对象作为它的参数。(有关其工作原理,请参阅 Chris S 的回答)Convert.ToInt32()
ArgumentNullException
当它的参数为 null 时也不会抛出Int32.Parse()
。这也意味着它Convert.ToInt32()
可能比 慢一点Int32.Parse()
,但实际上,除非您在循环中进行大量迭代,否则您永远不会注意到它。
回答by shahkalpesh
No difference as such.Convert.ToInt32()
calls int.Parse()
internally
没有区别。内部Convert.ToInt32()
调用int.Parse()
Except for one thing Convert.ToInt32()
returns 0
when argument is null
除了当参数为时Convert.ToInt32()
返回一件事0
null
Otherwise both work the same way
否则两者的工作方式相同
回答by BoltBait
TryParse is faster...
TryParse 更快...
The first of these functions, Parse, is one that should be familiar to any .Net developer. This function will take a string and attempt to extract an integer out of it and then return the integer. If it runs into something that it can't parse then it throws a FormatException or if the number is too large an OverflowException. Also, it can throw an ArgumentException if you pass it a null value.
TryParse is a new addition to the new .Net 2.0 framework that addresses some issues with the original Parse function. The main difference is that exception handling is very slow, so if TryParse is unable to parse the string it does not throw an exception like Parse does. Instead, it returns a Boolean indicating if it was able to successfully parse a number. So you have to pass into TryParse both the string to be parsed and an Int32 out parameter to fill in. We will use the profiler to examine the speed difference between TryParse and Parse in both cases where the string can be correctly parsed and in cases where the string cannot be correctly parsed.
The Convert class contains a series of functions to convert one base class into another. I believe that Convert.ToInt32(string) just checks for a null string (if the string is null it returns zero unlike the Parse) then just calls Int32.Parse(string). I'll use the profiler to confirm this and to see if using Convert as opposed to Parse has any real effect on performance.
其中第一个函数 Parse 是任何 .Net 开发人员都应该熟悉的。此函数将接受一个字符串并尝试从中提取一个整数,然后返回该整数。如果遇到无法解析的内容,则会抛出 FormatException 或者如果数字太大则引发 OverflowException。此外,如果您向它传递空值,它可能会抛出 ArgumentException。
TryParse 是新的 .Net 2.0 框架的新增功能,解决了原始 Parse 函数的一些问题。主要区别在于异常处理非常慢,因此如果 TryParse 无法解析字符串,它不会像 Parse 那样抛出异常。相反,它返回一个布尔值,指示它是否能够成功解析一个数字。因此,您必须将要解析的字符串和一个 Int32 输出参数传递给 TryParse。无法正确解析字符串。
Convert 类包含一系列将一个基类转换为另一个基类的函数。我相信 Convert.ToInt32(string) 只是检查空字符串(如果字符串为空,则与 Parse 不同,它返回零)然后只调用 Int32.Parse(string)。我将使用分析器来确认这一点,并查看使用 Convert 而不是 Parse 是否对性能有任何实际影响。
Hope this helps.
希望这可以帮助。
回答by Matthew Scharley
The difference is this:
区别在于:
Int32.Parse()
and Int32.TryParse()
can only convert strings. Convert.ToInt32()
can take any class that implements IConvertible
. If you pass it a string, then they are equivalent, except that you get extra overhead for type comparisons, etc. If you are converting strings, then TryParse()
is probably the better option.
Int32.Parse()
并且Int32.TryParse()
只能转换字符串。Convert.ToInt32()
可以采用任何实现IConvertible
. 如果你传递一个字符串,那么它们是等价的,除了类型比较等额外的开销。如果你正在转换字符串,那么TryParse()
可能是更好的选择。
回答by Chris S
Have a look in reflector:
看看反射器:
int.Parse("32"):
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"):
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.
正如第一条(Dave M 的)评论所说。
回答by shraddha dhuri
Convert.ToInt32 allows null value, it doesn't throw any errors Int.parse does not allow null value, it throws an ArgumentNullException error.
Convert.ToInt32 允许空值,它不会抛出任何错误 Int.parse 不允许空值,它会抛出一个 ArgumentNullException 错误。
回答by shashi shekhar
Convert.ToInt32
has 19 overloads or 19 different ways that you can call it. Maybe more in 2010 versions.
有 19 种重载或 19 种不同的调用方式。也许在 2010 版本中更多。
It will attempt to convert from the following TYPES;
它将尝试从以下类型转换;
Object, Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, String, Date
对象、布尔值、字符、SByte、字节、Int16、UInt16、Int32、UInt32、Int64、UInt64、Single、Double、Decimal、String、Date
and it also has a number of other methods; one to do with a number base and 2 methods involve a System.IFormatProvider
它还有许多其他方法;一个与数字基数有关,而 2 个方法涉及一个System.IFormatProvider
Parse on the other hand only has 4 overloads or 4 different ways you can call the method.
另一方面,解析只有 4 个重载或 4 种不同的方法可以调用该方法。
Integer.Parse( s As String)
Integer.Parse( s As String, style As System.Globalization.NumberStyles )
Integer.Parse( s As String, provider As System.IFormatProvider )
Integer.Parse( s As String, style As System.Globalization.NumberStyles, provider As System.IFormatProvider )
回答by Pradeep Kumar
for clarification open console application, just copy below code and paste it in static void Main(string[] args)
method, I hope you can understand
为了澄清打开控制台应用程序,只需复制以下代码并将其粘贴到 static void Main(string[] args)
方法中,希望您能理解
public class Program
{
static void Main(string[] args)
{
int result;
bool status;
string s1 = "12345";
Console.WriteLine("input1:12345");
string s2 = "1234.45";
Console.WriteLine("input2:1234.45");
string s3 = null;
Console.WriteLine("input3:null");
string s4 = "1234567899012345677890123456789012345667890";
Console.WriteLine("input4:1234567899012345677890123456789012345667890");
string s5 = string.Empty;
Console.WriteLine("input5:String.Empty");
Console.WriteLine();
Console.WriteLine("--------Int.Parse Methods Outputs-------------");
try
{
result = int.Parse(s1);
Console.WriteLine("OutPut1:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut1:"+ee.Message);
}
try
{
result = int.Parse(s2);
Console.WriteLine("OutPut2:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut2:" + ee.Message);
}
try
{
result = int.Parse(s3);
Console.WriteLine("OutPut3:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut3:" + ee.Message);
}
try
{
result = int.Parse(s4);
Console.WriteLine("OutPut4:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut4:" + ee.Message);
}
try
{
result = int.Parse(s5);
Console.WriteLine("OutPut5:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut5:" + ee.Message);
}
Console.WriteLine();
Console.WriteLine("--------Convert.To.Int32 Method Outputs-------------");
try
{
result= Convert.ToInt32(s1);
Console.WriteLine("OutPut1:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut1:" + ee.Message);
}
try
{
result = Convert.ToInt32(s2);
Console.WriteLine("OutPut2:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut2:" + ee.Message);
}
try
{
result = Convert.ToInt32(s3);
Console.WriteLine("OutPut3:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut3:" + ee.Message);
}
try
{
result = Convert.ToInt32(s4);
Console.WriteLine("OutPut4:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut4:" + ee.Message);
}
try
{
result = Convert.ToInt32(s5);
Console.WriteLine("OutPut5:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut5:" + ee.Message);
}
Console.WriteLine();
Console.WriteLine("--------TryParse Methods Outputs-------------");
try
{
status = int.TryParse(s1, out result);
Console.WriteLine("OutPut1:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut1:" + ee.Message);
}
try
{
status = int.TryParse(s2, out result);
Console.WriteLine("OutPut2:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut2:" + ee.Message);
}
try
{
status = int.TryParse(s3, out result);
Console.WriteLine("OutPut3:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut3:" + ee.Message);
}
try
{
status = int.TryParse(s4, out result);
Console.WriteLine("OutPut4:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut4:" + ee.Message);
}
try
{
status = int.TryParse(s5, out result);
Console.WriteLine("OutPut5:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut5:" + ee.Message);
}
Console.Read();
}
}
回答by Dale K
It depends on the parameter type. For example, I just discovered today that it will convert a char directly to int using its ASCII value. Not exactly the functionality I intended...
这取决于参数类型。例如,我今天刚刚发现它会使用其 ASCII 值将 char 直接转换为 int。不完全是我想要的功能......
YOU HAVE BEEN WARNED!
你被警告了!
public static int ToInt32(char value)
{
return (int)value;
}
Convert.ToInt32('1'); // Returns 49
int.Parse('1'); // Returns 1
回答by Sonu Rajpoot
Int32.parse(string)--->
Int32.parse(string)--->
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. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException. For example:
Int32.Parse (string s) 方法将数字的字符串表示形式转换为其等效的 32 位有符号整数。当 s 为空引用时,它将抛出 ArgumentNullException。如果 s 不是整数值,它将抛出 FormatException。当 s 代表一个小于 MinValue 或大于 MaxValue 的数字时,它会抛出 OverflowException。例如:
string s1 = "1234";
string s2 = "1234.65";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";
result = Int32.Parse(s1); //1234
result = Int32.Parse(s2); //FormatException
result = Int32.Parse(s3); //ArgumentNullException
result = Int32.Parse(s4); //OverflowException
Convert.ToInt32(string) -->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. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.
Convert.ToInt32(string) -->Convert.ToInt32(string s) 方法转换指定的 32 位有符号整数等效字符串表示形式。这样依次调用Int32.Parse()方法。当 s 为空引用时,它将返回 0 而不是抛出 ArgumentNullException。如果 s 不是整数值,它将抛出 FormatException。当 s 代表一个小于 MinValue 或大于 MaxValue 的数字时,它会抛出 OverflowException。
For example:
例如:
result = Convert.ToInt32(s1); // 1234
result = Convert.ToInt32(s2); // FormatException
result = Convert.ToInt32(s3); // 0
result = Convert.ToInt32(s4); // OverflowException