int.Parse()和Convert之间的主要区别是什么?ToInt32

  • int.Parse()Convert.ToInt32()的主要区别是什么?
  • 哪一个是首选
336220 次浏览

本身没有区别 Convert.ToInt32()在内部调用int.Parse()

除了一件事Convert.ToInt32()在参数为null时返回0

否则两者的工作方式是一样的

  • 如果你有一个字符串,并且你希望它总是一个整数(比如,如果某个web服务以字符串格式给你一个整数),你应该使用<强> # EYZ0 < / >强

  • 如果您正在从用户收集输入,您通常会使用<强> # EYZ0 < / >强,因为它允许您对用户输入无效输入时的情况进行更细粒度的控制。

  • <强> # EYZ0 < / >强以一个对象作为参数。(详见Chris S的回答)

    Convert.ToInt32()也不像Int32.Parse()那样在参数为空时抛出ArgumentNullException。这也意味着Convert.ToInt32()可能比Int32.Parse()慢一点,尽管在实践中,除非您在循环中进行了大量的迭代,否则您永远不会注意到它。

TryParse更快…

第一个函数Parse应该很熟悉 任何。net开发人员。此函数将接受一个字符串并尝试 从中提取一个整数,然后返回该整数。如果它运行 变成它无法解析的东西,然后抛出FormatException或者 如果数目太大,则出现OverflowException。此外,它可以抛出一个

TryParse是新。net 2.0框架的一个新添加,它解决了原始Parse函数的一些问题。主要的 区别在于异常处理非常慢,所以如果TryParse是 无法解析字符串时,它不会像parse一样抛出异常 所做的事。相反,它返回一个布尔值,指示它是否能够 成功解析数字。所以你必须把两个都传递到TryParse中 要解析的字符串和要填充的Int32输出参数。我们将 使用分析器检查TryParse和 在字符串可以正确解析的两种情况下进行解析 字符串不能正确解析的情况 Convert类包含一系列将一个基类转换为另一个基类的函数。我相信 Convert.ToInt32(string)只是检查一个空字符串(如果字符串 是空它返回零不像解析)然后只是调用 Int32.Parse(字符串)。我会用侧写器确认一下 如果使用Convert而不是Parse有任何实际效果 性能。< / p >

Source with example .

区别在于:

Int32.Parse()Int32.TryParse()只能转换字符串。Convert.ToInt32()可以采用实现IConvertible的任何类。如果传递给它一个字符串,那么它们是等效的,除了类型比较等额外开销。如果要转换字符串,那么TryParse()可能是更好的选择。

请看反射镜:

int.Parse (32):

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

这是一个调用:

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);
}

正如第一个(Dave M的)评论所说。

< p >转换。ToInt32允许空值,它不会抛出任何错误 Int。解析不允许空值,它会抛出ArgumentNullException错误
Convert.ToInt32

有19种重载或者19种不同的调用方式。2010年的版本可能会更多。

它将尝试从以下类型进行转换;

对象,Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64,单个,双精度,十进制,字符串,日期

它还有很多其他的方法;一个与数字基础和2个方法涉及System.IFormatProvider

另一方面,Parse只有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 )

为了澄清打开控制台应用程序,只需复制下面的代码并粘贴在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();
}
}

这取决于参数类型。例如,我今天刚刚发现,它将使用ASCII值直接将char转换为int。这不是我想要的功能…

我警告过你!

public static int ToInt32(char value)
{
return (int)value;
}


Convert.ToInt32('1'); // Returns 49
int.Parse('1'); // Returns 1

Int32.parse(字符串)——>

Int32。Parse (string s)方法将数字的字符串表示形式转换为等效的32位有符号整数。当s是空引用时,它将抛出ArgumentNullException。如果s不是整数值,则抛出FormatException。当s表示一个小于MinValue或大于MaxValue的数字时,它将抛出OverflowException。# EYZ0:

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(字符串)——> 转换。ToInt32(string s)方法将指定的字符串表示形式转换为等效的32位有符号整数。这将依次调用Int32。Parse()方法。当s是空引用时,它将返回0而不是抛出ArgumentNullException。如果s不是整数值,则抛出FormatException。当s表示的数字小于MinValue或大于MaxValue时,将抛出OverflowException

例如:< em > < / em >

 result = Convert.ToInt32(s1);    // 1234
result = Convert.ToInt32(s2);    // FormatException
result = Convert.ToInt32(s3);    // 0
result = Convert.ToInt32(s4);    // OverflowException

int。Parse (string s)

  • RANGE >中的整数返回整数值
  • 空值> argementnullexception
  • 格式不是> FormatException
  • 值不在RANGE > OverflowException

转换。ToInt32(字符串)

  • RANGE >中的整数返回整数值
  • 空值>返回“0”
  • 格式不是> FormatException
  • 值不在RANGE > OverflowException

bool isParsed = int。TryParse(string s,out res)

  • RANGE中的整数>返回整数值,isParsed = true
  • 空值>返回“0”,isParsed = false
  • 不是格式>返回"0",isParsed = false
  • 值不在RANGE >返回"0",isParsed = false

试试.....下面的代码

class Program
{
static void Main(string[] args)
{
string strInt = "24532";
string strNull = null;
string strWrongFrmt = "5.87";
string strAboveRange = "98765432123456";
int res;
try
{
// int.Parse() - TEST
res = int.Parse(strInt); // res = 24532
res = int.Parse(strNull); // System.ArgumentNullException
res = int.Parse(strWrongFrmt); // System.FormatException
res = int.Parse(strAboveRange); // System.OverflowException


// Convert.ToInt32(string s) - TEST
res = Convert.ToInt32(strInt); // res = 24532
res = Convert.ToInt32(strNull); // res = 0
res = Convert.ToInt32(strWrongFrmt); // System.FormatException
res = Convert.ToInt32(strAboveRange); //System.OverflowException


// int.TryParse(string s, out res) - Test
bool isParsed;
isParsed = int.TryParse(strInt, out res); // isParsed = true, res = 24532
isParsed = int.TryParse(strNull, out res); // isParsed = false, res = 0
isParsed = int.TryParse(strWrongFrmt, out res); // isParsed = false, res = 0
isParsed = int.TryParse(strAboveRange, out res); // isParsed = false, res = 0
}
catch(Exception e)
{
Console.WriteLine("Check this.\n" + e.Message);
}
}
下面是int.ParseConvert.ToInt32的详细信息: 假设,您有一个字符数组char[] a=['1','2','3','4'],并希望将每个元素转换为整数。 Convert.ToInt32(a[0])会给你一个数字49。它将其视为ASCII码 int.Parse(a[0])将为您提供正确的输出,即1

如果你有一个字符串数组string[] b=['1','2','3','4'],那么Convert.ToInt32int.Parse在输出中没有区别。两者都返回正确的整数。

Parse()方法提供了不能用于Convert()的数字样式。例如:

int i;
bool b = int.TryParse( "123-",
System.Globalization.NumberStyles.AllowTrailingSign,
System.Globalization.CultureInfo.InvariantCulture,
out i);

将解析带尾符号的数字,以便I == -123
后面的符号在ERP系统中很流行