[C#] 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()반환0null

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


답변

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()하는 경우 더 나은 옵션 일 수 있습니다.


답변

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

예제가있는 소스

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