int.Parse ()와 Convert.ToInt32의 주요 차이점은 무엇입니까


492
  • 사이의 주요 차이점은 무엇입니까 int.Parse()와는 Convert.ToInt32()?
  • 어느 것이 선호되어야 하는가

답변:


448
  • 문자열이 있고 항상 정수가 될 것으로 예상하는 경우 (예 : 일부 웹 서비스가 문자열 형식의 정수를 전달하는 경우)을 사용 Int32.Parse()합니다.

  • 사용자로부터 입력을 수집 Int32.TryParse()하는 경우 사용자가 유효하지 않은 입력을 입력 할 때 상황을보다 세밀하게 제어 할 수 있으므로 일반적으로을 사용 합니다.

  • Convert.ToInt32()인수로 객체를 취합니다. (작동 방식은 Chris S의 답변 참조)

    Convert.ToInt32()또한 ArgumentNullException인수가 null 인 경우 던지지 Int32.Parse()않습니다. 그것은 또한 수단 Convert.ToInt32()조금이라도보다 느린 아마 Int32.Parse()당신은 루프에서 반복 매우 많은 일을하지 않는 한, 실제로는하지만, 당신은 그것을 알 수 없을거야.


54
다른 사람들이 지적했듯이 Convert.ToInt32 (s)는 s가 null 일 때 예외를 throw하지 않지만 Parse ()는 예외를 throw합니다. 차이를 측정하지 않기 때문에 "약간 느리다"는 지점 옆에 있습니다.
Robert Paulson

4
고마워 Robert! 좀 더 완벽하게 답변을 편집하고 있습니다. 그러나 성능이 향상되는 한 중첩 루프에서 호출하면 속도의 차이를 감지 할 수 있습니다.
Dave Markle

5
실제로,이 ToInt32방법에는 유형의로드에 대한 과부하가 있기 때문에 그 중에서도 System.String유형을 식별하는 데 시간이 손실되지 않습니다. 실제 코드는 null 값과 int.Parse(value, CultureInfo.CurrentCulture)그 밖의 모든 것에 대해 0 만 반환 합니다.
Andreas Eriksson

6
@StealthRabbi : 문서의 "값 반환"섹션에서 : "값의 숫자에 해당하는 32 비트 부호있는 정수 또는 값이 널인 경우 0 (영)."
Dave Markle

3
당신의 언급을 삭제 해 주시기 바랍니다 Int32.TryParse()Convert.ToInt32()가 올바르지 않아. 문자열의 형식이 올바르지 않으면 Convert에서 예외가 발생합니다.
Dehalion

190

리플렉터를 살펴보십시오.

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) 의견에 따르면.


19
이전 답변에서 추측을 모두 제거해 주셔서 감사합니다.
bopapa_1979

1
"return default (int);"이 아니어야합니다. ?
Skorunka František

2
즉, Convert.ToInt32반환 0의 경우는 null방지하기 위해 int.Parse을 높이는에서 ArgumentNullException.
André Leria

4
@ SkorunkaFrantišek-표현식 default(int)은 본질적인 값이기 때문에 컴파일 타임에 평가됩니다 . 표현식 의 결과는 0이므로 컴파일러는 리터럴을 삽입합니다 0. IL 디스 어셈블리 도구는 더 잘 알 수 없으므로 문자 그대로 0 만 표시합니다.
antiduh

4
@ SkorunkaFrantišek 이것은 전적으로 다른 점입니다. 사용자가 반영된 코드를 복사하고있었습니다. 변경하면 컴파일 된 내용이 잘못 표시됩니다. 사용자에게 원본 소스가 있고 원본 소스에 default (int)가 있으면 이것이 사용자가 게시 한 것입니다.
rshadman

78

그런 차이가 없습니다. 내부
Convert.ToInt32()전화int.Parse()

인수가 하나 일 때만 Convert.ToInt32()반환0null

그렇지 않으면 둘 다 같은 방식으로 작동합니다


5
보다 정확하게 Convert.ToInt32(string)int.Parse내부적으로 전화하십시오 . Convert.ToInt32(object)그러나, 통화 ((IConvertible) value).ToInt32의 경우에 약간의 복잡한 ... string전화 Convert.ToInt32(string):
Timwi

3
예. Convert.ToInt32 (char)는 실제로 (int) 값을 반환하여 '1'을 49로 바꿉니다. 일반적으로 의도 한 기능은 아닙니다.
Dale K

32

int.Parse (문자열 s)

  • RANGE의 정수> 정수 값을 반환
  • 널값> ArguementNullException
  • 형식이 아님> FormatException
  • RANGE> OverflowException에없는 값

Convert.ToInt32 (string s)

  • RANGE의 정수> 정수 값을 반환
  • 널값> "0"을 리턴 함
  • 형식이 아님> FormatException
  • RANGE> OverflowException에없는 값

부울 isParsed = int.TryParse (string s, out res)

  • RANGE의 정수>는 정수 값을 반환합니다. isParsed = true
  • 널값> "0"을 리턴합니다. isParsed = false
  • 형식이 아님> "0"을 반환하면 isParsed = false
  • 범위 내에 있지 않은 값> "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);
        }
    }


22

차이점은 다음과 같습니다.

Int32.Parse()Int32.TryParse()단지 문자열을 변환 할 수 있습니다. Convert.ToInt32()구현하는 모든 클래스를 사용할 수 있습니다 IConvertible. 문자열을 전달하면 유형 비교 등을 위해 추가 오버 헤드가 발생한다는 점을 제외하고는 동등합니다. 문자열을 변환 TryParse()하는 경우 더 나은 옵션 일 수 있습니다.


9

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 


8

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)을 호출한다고 생각합니다. 프로파일 러를 사용하여이를 확인하고 구문 분석과 달리 변환을 사용하여 성능에 실제로 영향을 미치는지 확인합니다.

예제가있는 소스

도움이 되었기를 바랍니다.


3
링크에 대한 바로 문자 조작 및 비트 이동, 감사 - 당신은 TryParse에서 소스를 볼 때 실제로 어떤 전혀 예외 처리가 없습니다
크리스 S

2
이 벤치 마크에 따르면 Parse, TryParse 및 Convert는 2 백만 개 이상의 개체를 변환하지 않는 한 거의 같은 속도입니다.
무료 코더 24

4
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 )

2

매개 변수 유형에 따라 다릅니다. 예를 들어, 오늘 ASCII 값을 사용하여 char을 int로 직접 변환한다는 것을 알았습니다. 내가 의도 한 기능이 아닙니다 ...

경고를 받았습니다!

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

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

C #에서 char암시 적으로 변환 할 수 있습니까 string? 확실히 VB.NET에서 가능하므로 해당 언어의 프로그래머는 아마 기대 Convert.ToInt32("1"c)하고 Convert.ToInt32("1")동등 할 것입니다 . 그러나 C #에 암시 적 변환이 있다고 생각하지 않습니다.
supercat

암시 적으로 또는 명시 적으로 char을 문자열로 변환 할 수 없습니다. '1'.ToString () 또는 new string ('1 ', 1)을 호출해야합니다.
데일 K

3
C #에서 "경고"는 그다지 중요하지 않습니다. 그 언어는 charvb.net보다 값이 조금 더 가치가 있기 때문입니다 . vb.net에서는 암시 적 캐스트로 인해 Char와 사이에 인식되는 차이가 적습니다 String.
supercat

2

여기에 대한 세부 사항입니다 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출력에 차이가 없습니다. 둘 다 올바른 정수를 반환합니다.


1

Convert.ToInt32는 null 값을 허용하고 오류를 발생시키지 않습니다. Int.parse는 null 값을 허용하지 않으며 ArgumentNullException 오류를 발생시킵니다.


1

설명을 위해 오픈 콘솔 응용 프로그램을 보려면 코드 아래에 복사하여 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();
        }
    }

1

Parse () 메서드는 Convert ()에 사용할 수없는 숫자 스타일을 제공합니다. 예를 들면 다음과 같습니다.

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

i == -123
이 되도록 숫자를 후행 부호로 구문 분석합니다 . 후행 부호는 ERP 시스템에서 널리 사용됩니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.