답변:
문자열이 있고 항상 정수가 될 것으로 예상하는 경우 (예 : 일부 웹 서비스가 문자열 형식의 정수를 전달하는 경우)을 사용 Int32.Parse()
합니다.
사용자로부터 입력을 수집 Int32.TryParse()
하는 경우 사용자가 유효하지 않은 입력을 입력 할 때 상황을보다 세밀하게 제어 할 수 있으므로 일반적으로을 사용 합니다.
Convert.ToInt32()
인수로 객체를 취합니다. (작동 방식은 Chris S의 답변 참조)
Convert.ToInt32()
또한 ArgumentNullException
인수가 null 인 경우 던지지 Int32.Parse()
않습니다. 그것은 또한 수단 Convert.ToInt32()
조금이라도보다 느린 아마 Int32.Parse()
당신은 루프에서 반복 매우 많은 일을하지 않는 한, 실제로는하지만, 당신은 그것을 알 수 없을거야.
ToInt32
방법에는 유형의로드에 대한 과부하가 있기 때문에 그 중에서도 System.String
유형을 식별하는 데 시간이 손실되지 않습니다. 실제 코드는 null 값과 int.Parse(value, CultureInfo.CurrentCulture)
그 밖의 모든 것에 대해 0 만 반환 합니다.
Int32.TryParse()
에 Convert.ToInt32()
가 올바르지 않아. 문자열의 형식이 올바르지 않으면 Convert에서 예외가 발생합니다.
리플렉터를 살펴보십시오.
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 's) 의견에 따르면.
Convert.ToInt32
반환 0
의 경우는 null
방지하기 위해 int.Parse
을 높이는에서 ArgumentNullException
.
default(int)
은 본질적인 값이기 때문에 컴파일 타임에 평가됩니다 . 표현식 의 결과는 0
이므로 컴파일러는 리터럴을 삽입합니다 0
. IL 디스 어셈블리 도구는 더 잘 알 수 없으므로 문자 그대로 0 만 표시합니다.
그런 차이가 없습니다. 내부
Convert.ToInt32()
전화int.Parse()
인수가 하나 일 때만 Convert.ToInt32()
반환0
null
그렇지 않으면 둘 다 같은 방식으로 작동합니다
Convert.ToInt32(string)
는 int.Parse
내부적으로 전화하십시오 . Convert.ToInt32(object)
그러나, 통화 ((IConvertible) value).ToInt32
의 경우에 약간의 복잡한 ... string
전화 Convert.ToInt32(string)
:
아래 코드를 사용해보십시오 .....
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);
}
}
Int32.parse (문자열) --->
Int32.Parse (string s) 메서드는 숫자의 문자열 표현을 32 비트 부호있는 정수로 변환합니다. s가 null 참조 인 경우 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) 메서드는 지정된 문자열 표현을 32 비트 부호있는 정수로 변환합니다. 차례로 Int32.Parse () 메서드를 호출합니다. s가 null 참조 인 경우 ArgumentNullException을 발생시키지 않고 0을 반환합니다. s가 정수 값이 아닌 경우 FormatException이 발생합니다. s가 MinValue보다 작거나 MaxValue보다 큰 숫자를 나타내는 경우 OverflowException이 발생합니다.
예를 들면 다음과 같습니다.
result = Convert.ToInt32(s1); // 1234
result = Convert.ToInt32(s2); // FormatException
result = Convert.ToInt32(s3); // 0
result = Convert.ToInt32(s4); // OverflowException
TryParse가 더 빠릅니다 ...
이러한 기능 중 첫 번째 기능인 Parse는 모든 .Net 개발자에게 친숙한 기능입니다. 이 함수는 문자열을 가져 와서 정수를 추출한 다음 정수를 반환합니다. 구문 분석 할 수없는 무언가가 발생하면 FormatException이 발생하거나 숫자가 너무 큰 경우 OverflowException이 발생합니다. 또한 null 값을 전달하면 ArgumentException이 발생할 수 있습니다.
TryParse는 새로운 .Net 2.0 프레임 워크에 새로 추가되어 원래 구문 분석 기능의 일부 문제를 해결합니다. 가장 큰 차이점은 예외 처리가 매우 느리다는 점입니다. 따라서 TryParse가 문자열을 구문 분석 할 수없는 경우 구문 분석과 같이 예외가 발생하지 않습니다. 대신 숫자를 성공적으로 구문 분석 할 수 있는지 여부를 나타내는 부울을 반환합니다. 따라서 구문 분석 할 문자열과 채울 Int32 out 매개 변수를 모두 TryParse에 전달해야합니다. 프로파일 러를 사용하여 문자열을 올바르게 구문 분석 할 수있는 경우와 구문 분석시 구문 분석 간의 속도 차이를 검사합니다. 문자열을 올바르게 구문 분석 할 수 없습니다.
Convert 클래스에는 하나의 기본 클래스를 다른 기본 클래스로 변환하는 일련의 함수가 포함되어 있습니다. Convert.ToInt32 (string)은 null 문자열을 확인하고 (문자열이 null 인 경우 구문 분석과 달리 0을 반환) Int32.Parse (string)을 호출한다고 생각합니다. 프로파일 러를 사용하여이를 확인하고 구문 분석과 달리 변환을 사용하여 성능에 실제로 영향을 미치는지 확인합니다.
도움이 되었기를 바랍니다.
Convert.ToInt32
호출 할 수있는 19 개의 과부하 또는 19 가지의 다른 방법이 있습니다. 아마도 2010 버전에서는 더 많을 것입니다.
다음 유형에서 변환을 시도합니다.
개체, 부울, 문자, SByte, 바이트, Int16, UInt16, Int32, UInt32, Int64, UInt64, 단일, 이중, 10 진수, 문자열, 날짜
또한 여러 가지 다른 방법이 있습니다. 하나는 숫자 기반과 관련이 있으며 두 가지 방법에는System.IFormatProvider
반면 구문 분석에는 메서드를 호출 할 수있는 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 )
매개 변수 유형에 따라 다릅니다. 예를 들어, 오늘 ASCII 값을 사용하여 char을 int로 직접 변환한다는 것을 알았습니다. 내가 의도 한 기능이 아닙니다 ...
경고를 받았습니다!
public static int ToInt32(char value)
{
return (int)value;
}
Convert.ToInt32('1'); // Returns 49
int.Parse('1'); // Returns 1
char
암시 적으로 변환 할 수 있습니까 string
? 확실히 VB.NET에서 가능하므로 해당 언어의 프로그래머는 아마 기대 Convert.ToInt32("1"c)
하고 Convert.ToInt32("1")
동등 할 것입니다 . 그러나 C #에 암시 적 변환이 있다고 생각하지 않습니다.
char
vb.net보다 값이 조금 더 가치가 있기 때문입니다 . vb.net에서는 암시 적 캐스트로 인해 Char
와 사이에 인식되는 차이가 적습니다 String
.
여기에 대한 세부 사항입니다 int.Parse
과 Convert.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.ToInt32
과 int.Parse
출력에 차이가 없습니다. 둘 다 올바른 정수를 반환합니다.
설명을 위해 오픈 콘솔 응용 프로그램을 보려면 코드 아래에 복사하여 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();
}
}
Parse () 메서드는 Convert ()에 사용할 수없는 숫자 스타일을 제공합니다. 예를 들면 다음과 같습니다.
int i;
bool b = int.TryParse( "123-",
System.Globalization.NumberStyles.AllowTrailingSign,
System.Globalization.CultureInfo.InvariantCulture,
out i);
i == -123
이 되도록 숫자를 후행 부호로 구문 분석합니다 . 후행 부호는 ERP 시스템에서 널리 사용됩니다.