Programming

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

procodes 2020. 2. 15. 23:38
반응형

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


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

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

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

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

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


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

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()전화int.Parse()

인수가 하나 일 Convert.ToInt32()반환 0되는 것 하나를 제외하고null

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


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

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

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


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

예제가있는 소스

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


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 

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

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


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


설명을 위해 오픈 콘솔 응용 프로그램을 보려면 코드 아래에 복사하여 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 시스템에서 널리 사용됩니다.

참고 URL : https://stackoverflow.com/questions/199470/whats-the-main-difference-between-int-parse-and-convert-toint32



반응형