Int32.TryParse 메서드

정의

숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다. 반환 값은 작업의 성공 여부를 나타냅니다.

오버로드

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)

UTF-8 문자 범위를 값으로 구문 분석하려고 시도합니다.

TryParse(ReadOnlySpan<Char>, Int32)

지정된 스타일 및 문화권별 형식으로 된 숫자의 범위 표현을 해당하는 32비트 부호 있는 정수로 변환합니다. 반환 값은 변환의 성공 여부를 나타냅니다.

TryParse(String, Int32)

숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다. 반환 값은 변환의 성공 여부를 나타냅니다.

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32)

문자 범위를 값으로 구문 분석하려고 합니다.

TryParse(String, IFormatProvider, Int32)

문자열을 값으로 구문 분석하려고 합니다.

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Int32)

UTF-8 문자 범위를 값으로 구문 분석하려고 시도합니다.

TryParse(ReadOnlySpan<Byte>, Int32)

숫자의 문자열 표현을 포함하는 UTF-8 문자 범위를 해당하는 32비트 부호 있는 정수로 변환하려고 합니다.

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int32)

지정된 스타일 및 문화권별 형식으로 된 숫자의 범위 표현을 해당하는 32비트 부호 있는 정수로 변환합니다. 반환 값은 변환의 성공 여부를 나타냅니다.

TryParse(String, NumberStyles, IFormatProvider, Int32)

지정된 스타일 및 문화권별 형식으로 된 숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다. 반환 값은 변환의 성공 여부를 나타냅니다.

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)

UTF-8 문자 범위를 값으로 구문 분석하려고 시도합니다.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = IUtf8SpanParsable<int>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, out int result);
static member TryParse : ReadOnlySpan<byte> * IFormatProvider * int -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider, ByRef result As Integer) As Boolean

매개 변수

utf8Text
ReadOnlySpan<Byte>

구문 분석할 UTF-8자의 범위입니다.

provider
IFormatProvider

utf8Text에 대한 문화권별 서식 정보를 제공하는 개체입니다.

result
Int32

반환 시 에는 성공적으로 구문 분석 utf8Text 한 결과 또는 실패 시 정의되지 않은 값이 포함됩니다.

반환

true 가 성공적으로 구문 분석되었으면 utf8Text 이고, false그렇지 않으면 입니다.

적용 대상

TryParse(ReadOnlySpan<Char>, Int32)

지정된 스타일 및 문화권별 형식으로 된 숫자의 범위 표현을 해당하는 32비트 부호 있는 정수로 변환합니다. 반환 값은 변환의 성공 여부를 나타냅니다.

public:
 static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] int % result);
public static bool TryParse (ReadOnlySpan<char> s, out int result);
static member TryParse : ReadOnlySpan<char> * int -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As Integer) As Boolean

매개 변수

s
ReadOnlySpan<Char>

변환할 숫자를 나타내는 문자를 포함하는 범위입니다.

result
Int32

이 메서드는 변환이 성공한 경우 s에 포함된 숫자의 32비트 부호 있는 정수 값을 반환하고, 변환이 실패한 경우 0을 반환합니다. 매개 변수가 또는 Emptynull 이거나 와 호환style되는 형식이 아니거나 Int32.MinValue보다 작거나 Int32.MaxValue보다 큰 숫자를 나타내는 경우 s 변환 실패합니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다. 원래 result에 제공된 모든 값을 덮어쓰게 됩니다.

반환

s이(가) 성공적으로 변환되었으면 true이고, 그렇지 않으면 false입니다.

적용 대상

TryParse(String, Int32)

숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다. 반환 값은 변환의 성공 여부를 나타냅니다.

public:
 static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] int % result);
public static bool TryParse (string s, out int result);
public static bool TryParse (string? s, out int result);
static member TryParse : string * int -> bool
Public Shared Function TryParse (s As String, ByRef result As Integer) As Boolean

매개 변수

s
String

변환할 숫자가 포함된 문자열입니다.

result
Int32

이 메서드는 변환이 성공한 경우 s에 포함된 숫자의 32비트 부호 있는 정수 값을 반환하고, 변환이 실패한 경우 0을 반환합니다. 매개 변수가 또는 Emptynull 올바른 형식이 아니거나 Int32.MinValue보다 작거나 Int32.MaxValue보다 큰 숫자를 나타내는 경우 s 변환 실패합니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다. 원래 result에 제공된 모든 값을 덮어쓰게 됩니다.

반환

s이(가) 성공적으로 변환되었으면 true이고, 그렇지 않으면 false입니다.

예제

다음 예제에서는 여러 문자열 값을 사용하여 메서드를 호출 Int32.TryParse(String, Int32) 합니다.

using namespace System;


   void TryToParse(String^ value)
   {
      Int32 number;
      bool result = Int32::TryParse(value, number);
      if (result) {
         Console::WriteLine("Converted '{0}' to {1}.", value, number);
      }
      else {
         if (value == nullptr) value = "";
         Console::WriteLine("Attempted conversion of '{0}' failed.", value);
      }
   }


void main()
{
      TryToParse(nullptr);
      TryToParse("160519");
      TryToParse("9432.0");
      TryToParse("16,667");
      TryToParse("   -322   ");
      TryToParse("+4302");
      TryToParse("(100);");
      TryToParse("01FA");
}
// The example displays the following output:
//      Attempted conversion of '' failed.
//      Converted '160519' to 160519.
//      Attempted conversion of '9432.0' failed.
//      Attempted conversion of '16,667' failed.
//      Converted '   -322   ' to -322.
//      Converted '+4302' to 4302.
//      Attempted conversion of '(100);' failed.
//      Attempted conversion of '01FA' failed.
using System;

public class Example
{
   public static void Main()
   {
      string[] values = { null, "160519", "9432.0", "16,667",
                          "   -322   ", "+4302", "(100);", "01FA" };
      foreach (var value in values)
      {
         int number;

         bool success = int.TryParse(value, out number);
         if (success)
         {
            Console.WriteLine($"Converted '{value}' to {number}.");
         }
         else
         {
            Console.WriteLine($"Attempted conversion of '{value ?? "<null>"}' failed.");
         }
      }
   }
}
// The example displays the following output:
//       Attempted conversion of '<null>' failed.
//       Converted '160519' to 160519.
//       Attempted conversion of '9432.0' failed.
//       Attempted conversion of '16,667' failed.
//       Converted '   -322   ' to -322.
//       Converted '+4302' to 4302.
//       Attempted conversion of '(100);' failed.
//       Attempted conversion of '01FA' failed.
open System

let values = 
   [ null; "160519"; "9432.0"; "16,667"
     "   -322   "; "+4302"; "(100);"; "01FA" ]
for value in values do
    match Int32.TryParse value with
    | true, number -> 
        printfn $"Converted '{value}' to {number}."
    | _ -> 
        printfn $"""Attempted conversion of '{if isNull value then "<null>" else value}' failed."""
         
// The example displays the following output:
//       Attempted conversion of '<null>' failed.
//       Converted '160519' to 160519.
//       Attempted conversion of '9432.0' failed.
//       Attempted conversion of '16,667' failed.
//       Converted '   -322   ' to -322.
//       Converted '+4302' to 4302.
//       Attempted conversion of '(100);' failed.
//       Attempted conversion of '01FA' failed.
Module Example
   Public Sub Main()
      Dim values() As String = { Nothing, "160519", "9432.0", "16,667",
                                 "   -322   ", "+4302", "(100);", 
                                 "01FA" }

      For Each value In values
         Dim number As Integer
    
         Dim success As Boolean = Int32.TryParse(value, number)
         If success Then
            Console.WriteLine("Converted '{0}' to {1}.", value, number)
         Else
            Console.WriteLine("Attempted conversion of '{0}' failed.", 
                              If(value ,"<null>"))
         End If     
      Next
   End Sub
End Module
' The example displays the following output to the console:
'       Attempted conversion of '<null>' failed.
'       Converted '160519' to 160519.
'       Attempted conversion of '9432.0' failed.
'       Attempted conversion of '16,667' failed.
'       Converted '   -322   ' to -322.
'       Converted '+4302' to 4302.
'       Attempted conversion of '(100)' failed.
'       Attempted conversion of '01FA' failed.

이 예제에서 메서드가 TryParse(String, Int32) 변환할 수 없는 문자열 중 일부는 다음과 같습니다.

  • "9432.0". 문자열에 10진수 구분 기호를 포함할 수 없으므로 변환이 실패합니다. 정수 자릿수만 포함해야 합니다.

  • "16,667". 문자열에 그룹 구분 기호를 포함할 수 없으므로 변환이 실패합니다. 정수 자릿수만 포함해야 합니다.

  • "(100)". 문자열에 현재 문화권 NumberFormatInfo.NegativeSignNumberFormatInfo.NumberNegativePattern 속성으로 정의된 기호 이외의 음수 기호를 포함할 수 없으므로 변환이 실패합니다.

  • "01FA". 문자열에 16진수 숫자를 포함할 수 없으므로 변환이 실패합니다. 10진수만 포함해야 합니다.

설명

메서드는 TryParse 메서드와 Parse 비슷하지만 변환에 TryParse 실패할 경우 메서드가 예외를 throw하지 않습니다. 예외 처리를 사용하여 유효하지 않고 성공적으로 구문 분석할 수 없는 경우 s 를 테스트 FormatException 할 필요가 없습니다.

매개 변수에는 s 다음과 같은 다양한 형식이 포함됩니다.

[ws] [sign]digits[ws]

대괄호([ 및 ])의 항목은 선택 사항입니다. 다음 표에서는 각 요소에 대해 설명합니다.

요소 설명
ws 선택적 공백입니다.
sign 선택적 기호입니다.
숫자 0에서 9 사이의 숫자 시퀀스입니다.

매개 변수는 s 스타일을 사용하여 해석됩니다 NumberStyles.Integer . 소수 자릿수 외에도 선행 기호와 함께 선행 및 후행 공백만 허용됩니다. 스타일 요소를 에 있을 s수 있는 문화권별 서식 정보와 함께 명시적으로 정의하려면 메서드를 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) 사용합니다.

s 매개 변수는 현재 시스템 문화권에 대해 초기화된 개체의 NumberFormatInfo 서식 정보를 사용하여 구문 분석됩니다. 자세한 내용은 CurrentInfo를 참조하세요.

메서드의 TryParse 이 오버로드는 매개 변수의 모든 숫자를 s 10진수로 해석합니다. 16진수의 문자열 표현을 구문 분석하려면 오버로드를 호출합니다 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) .

추가 정보

적용 대상

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32)

문자 범위를 값으로 구문 분석하려고 합니다.

public:
 static bool TryParse(ReadOnlySpan<char> s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = ISpanParsable<int>::TryParse;
public static bool TryParse (ReadOnlySpan<char> s, IFormatProvider? provider, out int result);
static member TryParse : ReadOnlySpan<char> * IFormatProvider * int -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), provider As IFormatProvider, ByRef result As Integer) As Boolean

매개 변수

s
ReadOnlySpan<Char>

구문 분석할 문자의 범위입니다.

provider
IFormatProvider

s에 대한 문화권별 서식 정보를 제공하는 개체입니다.

result
Int32

이 메서드가 반환될 때 에는 성공적으로 구문 분석 s한 결과 또는 실패 시 정의되지 않은 값이 포함됩니다.

반환

true 가 성공적으로 구문 분석되었으면 s 이고, false그렇지 않으면 입니다.

적용 대상

TryParse(String, IFormatProvider, Int32)

문자열을 값으로 구문 분석하려고 합니다.

public:
 static bool TryParse(System::String ^ s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = IParsable<int>::TryParse;
public static bool TryParse (string? s, IFormatProvider? provider, out int result);
static member TryParse : string * IFormatProvider * int -> bool
Public Shared Function TryParse (s As String, provider As IFormatProvider, ByRef result As Integer) As Boolean

매개 변수

s
String

구문 분석할 문자열입니다.

provider
IFormatProvider

s에 대한 문화권별 서식 정보를 제공하는 개체입니다.

result
Int32

이 메서드가 반환될 때 실패 시 성공적으로 구문 분석 s 한 결과 또는 정의되지 않은 값이 포함됩니다.

반환

true 가 성공적으로 구문 분석되었으면 s 이고, false그렇지 않으면 입니다.

적용 대상

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Int32)

UTF-8 문자 범위를 값으로 구문 분석하려고 시도합니다.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);
static member TryParse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider * int -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean

매개 변수

utf8Text
ReadOnlySpan<Byte>

구문 분석할 UTF-8자의 범위입니다.

style
NumberStyles

utf8Text있을 수 있는 숫자 스타일의 비트 조합입니다.

provider
IFormatProvider

utf8Text에 대한 문화권별 서식 정보를 제공하는 개체입니다.

result
Int32

반환 시 에는 성공적으로 구문 분석 utf8Text 한 결과 또는 실패 시 정의되지 않은 값이 포함됩니다.

반환

true 가 성공적으로 구문 분석되었으면 utf8Text 이고, false그렇지 않으면 입니다.

적용 대상

TryParse(ReadOnlySpan<Byte>, Int32)

숫자의 문자열 표현을 포함하는 UTF-8 문자 범위를 해당하는 32비트 부호 있는 정수로 변환하려고 합니다.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, [Runtime::InteropServices::Out] int % result);
public static bool TryParse (ReadOnlySpan<byte> utf8Text, out int result);
static member TryParse : ReadOnlySpan<byte> * int -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), ByRef result As Integer) As Boolean

매개 변수

utf8Text
ReadOnlySpan<Byte>

변환할 숫자를 나타내는 UTF-8 문자를 포함하는 범위입니다.

result
Int32

이 메서드가 반환될 때 변환에 성공한 경우 에 포함된 수에 해당하는 32비트 부호 있는 utf8Text 정수 값이 포함되거나 변환에 실패한 경우 0이 포함됩니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다. 원래 결과에 제공된 모든 값을 덮어쓰게 됩니다.

반환

utf8Text이(가) 성공적으로 변환되었으면 true이고, 그렇지 않으면 false입니다.

적용 대상

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int32)

지정된 스타일 및 문화권별 형식으로 된 숫자의 범위 표현을 해당하는 32비트 부호 있는 정수로 변환합니다. 반환 값은 변환의 성공 여부를 나타냅니다.

public:
 static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result);
public:
 static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider provider, out int result);
static member TryParse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider * int -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean

매개 변수

s
ReadOnlySpan<Char>

변환할 숫자를 나타내는 문자를 포함하는 범위입니다. style에서 지정된 스타일을 사용하여 해석하는 범위입니다.

style
NumberStyles

s에 나타날 수 있는 스타일 요소를 나타내는 열거형 값의 비트 조합입니다. 지정할 일반적인 값은 Integer입니다.

provider
IFormatProvider

s에 대한 문화권별 형식 지정 정보를 제공하는 개체입니다.

result
Int32

이 메서드는 변환이 성공한 경우 s에 포함된 숫자의 32비트 부호 있는 정수 값을 반환하고, 변환이 실패한 경우 0을 반환합니다. 매개 변수가 또는 Emptynull 이거나 와 호환style되는 형식이 아니거나 Int32.MinValue보다 작거나 Int32.MaxValue보다 큰 숫자를 나타내는 경우 s 변환 실패합니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다. 원래 result에 제공된 모든 값을 덮어쓰게 됩니다.

반환

s이(가) 성공적으로 변환되었으면 true이고, 그렇지 않으면 false입니다.

적용 대상

TryParse(String, NumberStyles, IFormatProvider, Int32)

지정된 스타일 및 문화권별 형식으로 된 숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다. 반환 값은 변환의 성공 여부를 나타냅니다.

public:
 static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result);
public:
 static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;
public static bool TryParse (string s, System.Globalization.NumberStyles style, IFormatProvider provider, out int result);
public static bool TryParse (string? s, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);
static member TryParse : string * System.Globalization.NumberStyles * IFormatProvider * int -> bool
Public Shared Function TryParse (s As String, style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean

매개 변수

s
String

변환할 숫자가 포함된 문자열입니다. 이 문자열은 style이 지정하는 스타일을 사용하여 해석됩니다.

style
NumberStyles

s에 나타날 수 있는 스타일 요소를 나타내는 열거형 값의 비트 조합입니다. 지정할 일반적인 값은 Integer입니다.

provider
IFormatProvider

s에 대한 문화권별 형식 지정 정보를 제공하는 개체입니다.

result
Int32

이 메서드는 변환이 성공한 경우 s에 포함된 숫자의 32비트 부호 있는 정수 값을 반환하고, 변환이 실패한 경우 0을 반환합니다. 매개 변수가 또는 Emptynull 이거나 와 호환style되는 형식이 아니거나 Int32.MinValue보다 작거나 Int32.MaxValue보다 큰 숫자를 나타내는 경우 s 변환 실패합니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다. 원래 result에 제공된 모든 값을 덮어쓰게 됩니다.

반환

s이(가) 성공적으로 변환되었으면 true이고, 그렇지 않으면 false입니다.

예외

styleNumberStyles 값이 아닙니다.

또는

styleAllowHexSpecifierHexNumber 값의 조합이 아닙니다.

예제

다음 예제에서는 다양한 문자열과 NumberStyles 값을 사용하여 메서드를 호출 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) 합니다.

using namespace System;
using namespace System::Globalization;

void CallTryParse(String^ stringToConvert, NumberStyles styles)
{
      Int32 number;
      CultureInfo^ provider;

      // If currency symbol is allowed, use en-US culture. 
      if (((Int32) (styles & NumberStyles::AllowCurrencySymbol)) > 0)
         provider = gcnew CultureInfo("en-US");
      else
         provider = CultureInfo::InvariantCulture;

      bool result = Int32::TryParse(stringToConvert, styles, 
                                   provider, number);
      if (result)
         Console::WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
      else
         Console::WriteLine("Attempted conversion of '{0}' failed.", 
                           Convert::ToString(stringToConvert));
}

void main()
{
      String^ numericString;
      NumberStyles styles;

      numericString = "106779";
      styles = NumberStyles::Integer;
      CallTryParse(numericString, styles);

      numericString = "-30677";
      styles = NumberStyles::None;
      CallTryParse(numericString, styles);

      styles = NumberStyles::AllowLeadingSign;
      CallTryParse(numericString, styles);

      numericString = "301677-";
      CallTryParse(numericString, styles);

      styles = styles | NumberStyles::AllowTrailingSign;
      CallTryParse(numericString, styles);

      numericString = "$10634";
      styles = NumberStyles::Integer;
      CallTryParse(numericString, styles);

      styles = NumberStyles::Integer | NumberStyles::AllowCurrencySymbol;
      CallTryParse(numericString, styles);

      numericString = "10345.00";
      styles = NumberStyles::Integer | NumberStyles::AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "10345.72";
      styles = NumberStyles::Integer | NumberStyles::AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "22,593"; 
      styles = NumberStyles::Integer | NumberStyles::AllowThousands;
      CallTryParse(numericString, styles);

      numericString = "12E-01";
      styles = NumberStyles::Integer | NumberStyles::AllowExponent;
      CallTryParse(numericString, styles); 

      numericString = "12E03";
      CallTryParse(numericString, styles); 

      numericString = "80c1";
      CallTryParse(numericString, NumberStyles::HexNumber);

      numericString = "0x80C1";
      CallTryParse(numericString, NumberStyles::HexNumber);      
      Console::ReadLine();
}
// The example displays the following output:
//      Converted '106779' to 106779.
//      Attempted conversion of '-30677' failed.
//      Converted '-30677' to -30677.
//      Attempted conversion of '301677-' failed.
//      Converted '301677-' to -301677.
//      Attempted conversion of '$10634' failed.
//      Converted '$10634' to 10634.
//      Converted '10345.00' to 10345.
//      Attempted conversion of '10345.72' failed.
//      Converted '22,593' to 22593.
//      Attempted conversion of '12E-01' failed.
//      Converted '12E03' to 12000.
//      Converted '80c1' to 32961.
//      Attempted conversion of '0x80C1' failed.
using System;
using System.Globalization;

public class StringParsing
{
   public static void Main()
   {
      string numericString;
      NumberStyles styles;

      numericString = "106779";
      styles = NumberStyles.Integer;
      CallTryParse(numericString, styles);

      numericString = "-30677";
      styles = NumberStyles.None;
      CallTryParse(numericString, styles);

      styles = NumberStyles.AllowLeadingSign;
      CallTryParse(numericString, styles);

      numericString = "301677-";
      CallTryParse(numericString, styles);

      styles = styles | NumberStyles.AllowTrailingSign;
      CallTryParse(numericString, styles);

      numericString = "$10634";
      styles = NumberStyles.Integer;
      CallTryParse(numericString, styles);

      styles = NumberStyles.Integer | NumberStyles.AllowCurrencySymbol;
      CallTryParse(numericString, styles);

      numericString = "10345.00";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "10345.72";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "22,593";
      styles = NumberStyles.Integer | NumberStyles.AllowThousands;
      CallTryParse(numericString, styles);

      numericString = "12E-01";
      styles = NumberStyles.Integer | NumberStyles.AllowExponent;
      CallTryParse(numericString, styles);

      numericString = "12E03";
      CallTryParse(numericString, styles);

      numericString = "80c1";
      CallTryParse(numericString, NumberStyles.HexNumber);

      numericString = "0x80C1";
      CallTryParse(numericString, NumberStyles.HexNumber);
   }

   private static void CallTryParse(string stringToConvert, NumberStyles styles)
   {
      CultureInfo provider;

      // If currency symbol is allowed, use en-US culture.
      if ((styles & NumberStyles.AllowCurrencySymbol) > 0)
         provider = new CultureInfo("en-US");
      else
         provider = CultureInfo.InvariantCulture;

      bool success = int.TryParse(stringToConvert, styles,
                                   provider, out int number);
      if (success)
         Console.WriteLine($"Converted '{stringToConvert}' to {number}.");
      else
         Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed.");
   }
}
// The example displays the following output to the console:
//       Converted '106779' to 106779.
//       Attempted conversion of '-30677' failed.
//       Converted '-30677' to -30677.
//       Attempted conversion of '301677-' failed.
//       Converted '301677-' to -301677.
//       Attempted conversion of '$10634' failed.
//       Converted '$10634' to 10634.
//       Converted '10345.00' to 10345.
//       Attempted conversion of '10345.72' failed.
//       Converted '22,593' to 22593.
//       Attempted conversion of '12E-01' failed.
//       Converted '12E03' to 12000.
//       Converted '80c1' to 32961.
//       Attempted conversion of '0x80C1' failed.
open System
open System.Globalization

let callTryParse (stringToConvert: string) styles =
    let provider =
        // If currency symbol is allowed, use en-US culture.
        if int (styles &&& NumberStyles.AllowCurrencySymbol) > 0 then
            CultureInfo "en-US"
        else
            CultureInfo.InvariantCulture

    match Int32.TryParse(stringToConvert, styles, provider) with
    | true, number ->
        printfn $"Converted '{stringToConvert}' to {number}."
    | _ ->
        printfn $"Attempted conversion of '{stringToConvert}' failed."

[<EntryPoint>]
let main _ =
    let numericString = "106779"
    let styles = NumberStyles.Integer
    callTryParse numericString styles

    let numericString = "-30677"
    let styles = NumberStyles.None
    callTryParse numericString styles

    let styles = NumberStyles.AllowLeadingSign
    callTryParse numericString styles

    let numericString = "301677-"
    callTryParse numericString styles

    let styles = styles ||| NumberStyles.AllowTrailingSign
    callTryParse numericString styles

    let numericString = "$10634"
    let styles = NumberStyles.Integer
    callTryParse numericString styles

    let styles = NumberStyles.Integer ||| NumberStyles.AllowCurrencySymbol
    callTryParse numericString styles

    let numericString = "10345.00"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
    callTryParse numericString styles

    let numericString = "10345.72"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
    callTryParse numericString styles

    let numericString = "22,593"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowThousands
    callTryParse numericString styles

    let numericString = "12E-01"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowExponent
    callTryParse numericString styles

    let numericString = "12E03"
    callTryParse numericString styles

    let numericString = "80c1"
    callTryParse numericString NumberStyles.HexNumber

    let numericString = "0x80C1"
    callTryParse numericString NumberStyles.HexNumber

    0

// The example displays the following output to the console:
//       Converted '106779' to 106779.
//       Attempted conversion of '-30677' failed.
//       Converted '-30677' to -30677.
//       Attempted conversion of '301677-' failed.
//       Converted '301677-' to -301677.
//       Attempted conversion of '$10634' failed.
//       Converted '$10634' to 10634.
//       Converted '10345.00' to 10345.
//       Attempted conversion of '10345.72' failed.
//       Converted '22,593' to 22593.
//       Attempted conversion of '12E-01' failed.
//       Converted '12E03' to 12000.
//       Converted '80c1' to 32961.
//       Attempted conversion of '0x80C1' failed.
Imports System.Globalization

Module StringParsing
   Public Sub Main()
      Dim numericString As String
      Dim styles As NumberStyles
      
      numericString = "106779"
      styles = NumberStyles.Integer
      CallTryParse(numericString, styles)
      
      numericString = "-30677"
      styles = NumberStyles.None
      CallTryParse(numericString, styles)
      
      styles = NumberStyles.AllowLeadingSign
      CallTryParse(numericString, styles)
      
      numericString = "301677-"
      CallTryParse(numericString, styles)
      
      styles = styles Or NumberStyles.AllowTrailingSign
      CallTryParse(numericString, styles)
      
      numericString = "$10634"
      styles = NumberStyles.Integer
      CallTryParse(numericString, styles)
      
      styles = NumberStyles.Integer Or NumberStyles.AllowCurrencySymbol
      CallTryParse(numericString, styles)

      numericString = "10345.00"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)
      
      numericString = "10345.72"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)

      numericString = "22,593" 
      styles = NumberStyles.Integer Or NumberStyles.AllowThousands
      CallTryParse(numericString, styles)
      
      numericString = "12E-01"
      styles = NumberStyles.Integer Or NumberStyles.AllowExponent
      CallTryParse(numericString, styles) 
          
      numericString = "12E03"
      CallTryParse(numericString, styles) 
      
      numericString = "80c1"
      CallTryParse(numericString, NumberStyles.HexNumber)
      
      numericString = "0x80C1"
      CallTryParse(numericString, NumberStyles.HexNumber)
   End Sub
   
   Private Sub CallTryParse(stringToConvert As String, styles AS NumberStyles)
      Dim number As Integer
      Dim provider As CultureInfo
      
      ' If currency symbol is allowed, use en-US culture.
      If CBool(styles And NumberStyles.AllowCurrencySymbol) Then
         provider = CultureInfo.CurrentCulture
      Else
         provider = New CultureInfo("en-US")
      End If
      
      Dim result As Boolean = Int32.TryParse(stringToConvert, styles, _
                                             provider, number)
      If result Then
         Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
      Else
         Console.WriteLine("Attempted conversion of '{0}' failed.", _
                           Convert.ToString(stringToConvert))
      End If                                                                           
   End Sub
End Module
' The example displays the following output to the console:
'       Converted '106779' to 106779.
'       Attempted conversion of '-30677' failed.
'       Converted '-30677' to -30677.
'       Attempted conversion of '301677-' failed.
'       Converted '301677-' to -301677.
'       Attempted conversion of '$10634' failed.
'       Converted '$10634' to 10634.
'       Converted '10345.00' to 10345.
'       Attempted conversion of '10345.72' failed.
'       Converted '22,593' to 22593.
'       Attempted conversion of '12E-01' failed.
'       Converted '12E03' to 12000.
'       Converted '80c1' to 32961.
'       Attempted conversion of '0x80C1' failed.

설명

메서드는 TryParse 메서드와 Parse 비슷하지만 변환에 TryParse 실패할 경우 메서드가 예외를 throw하지 않습니다. 이는 유효하지 않고 성공적으로 구문 분석할 수 없는 경우 s 예외 처리를 사용하여 에 대해 FormatException 테스트할 필요가 없습니다.

매개 변수는 style 구문 분석 작업이 성공하기 위해 매개 변수에 s 허용되는 스타일 요소(예: 공백 또는 양수 또는 음수 기호)를 정의합니다. 열거형의 비트 플래그 NumberStyles 조합이어야 합니다. 의 값 style에 따라 매개 변수에 s 다음 요소가 포함될 수 있습니다.

[ws] [$] [기호] [digits,]digits[.fractional_digits][e[sign]digits][ws]

또는 매개 변수에 가 포함된 경우 입니다 styleAllowHexSpecifier.

[ws]hexdigits[ws]

대괄호([ 및 ])의 항목은 선택 사항입니다. 다음 표에서는 각 요소에 대해 설명합니다.

요소 설명
ws 선택적 공백입니다. 플래그가 포함된 경우 의 s 시작 부분에 공백이 표시되거나, 플래그가 NumberStyles.AllowLeadingWhite 포함된 경우 styles 끝에 공백이 NumberStyles.AllowTrailingWhite 표시될 수 style 있습니다.
$ 문화권별 통화 기호입니다. 문자열의 위치는 매개 변수의 메서드 provider 에서 반환된 NumberFormatInfo 개체의 속성에 GetFormat 의해 CurrencyPositivePattern 정의됩니다. 플래그가 포함된 경우 style 통화 기호가 NumberStyles.AllowCurrencySymbols 나타날 수 있습니다.
sign 선택적 기호입니다. 또는 NumberStyles.AllowTrailingSign 플래그가 포함된 경우 style 기호 기호가 NumberStyles.AllowLeadingSigns 나타날 수 있습니다.
숫자 0에서 9까지의 숫자 시퀀스입니다.
, 문화권별 천 단위 구분 기호입니다. 에 지정된 provider 문화권의 천 단위 구분 기호가 플래그를 포함하는 NumberStyles.AllowThousands 경우 styles 나타날 수 있습니다.
. 문화권별 소수점 기호입니다. 에 지정된 provider 문화권의 소수점 기호가 플래그를 포함하는 NumberStyles.AllowDecimalPoint 경우 styles 나타날 수 있습니다.
fractional_digits 숫자 0이 하나 이상 발생합니다. 소수 자릿수는 플래그가 포함된 경우에만 styles 표시할 NumberStyles.AllowDecimalPoint 수 있습니다.
e 값이 지수 표기법으로 표시됨을 나타내는 'e' 또는 'E' 문자입니다. 플래그가 포함된 경우 style 매개 변수는 s 지수 표기법으로 NumberStyles.AllowExponent 숫자를 나타낼 수 있습니다.
hexdigits 0에서 f까지 또는 0부터 F까지의 16진수 숫자 시퀀스입니다.

참고

의 종결 NUL(U+0000) 문자는 인수 값 style 에 관계없이 구문 분석 작업에서 s 무시됩니다.

10진수만 있는 문자열(플래그에 NumberStyles.None 해당)은 항상 성공적으로 구문 분석됩니다. 나머지 NumberStyles 멤버의 대부분은 이 입력 문자열에 있을 수 있지만 필요하지 않은 요소를 제어합니다. 다음 표에서는 개별 NumberStyles 멤버가 에 s있을 수 있는 요소에 미치는 영향을 나타냅니다.

복합이 아닌 NumberStyles 값 숫자 외에 에서 허용되는 요소
NumberStyles.None 10진수만.
NumberStyles.AllowDecimalPoint 소수점(.) 및 fractional_digits 요소입니다. 그러나 fractional_digits 하나 이상의 숫자로만 구성되어야 합니다. 그렇지 않으면 메서드가 를 반환 false합니다.
NumberStyles.AllowExponent 매개 변수는 s 지수 표기법을 사용할 수도 있습니다. 지수 표기법의 숫자를 나타내는 경우 s 0이 아닌 소수 구성 요소가 없는 데이터 형식 범위 내의 Int32 정수를 나타내야 합니다.
NumberStyles.AllowLeadingWhite 의 시작 부분에 있는 ws 요소입니다 s.
NumberStyles.AllowTrailingWhite 의 끝에 있는 ws 요소입니다 s.
NumberStyles.AllowLeadingSign 숫자 앞에 기호가 나타날 수 있습니다.
NumberStyles.AllowTrailingSign 숫자 다음에 기호가 나타날 수 있습니다.
NumberStyles.AllowParentheses 숫자 값을 묶는 괄호 형식의 기호 요소입니다.
NumberStyles.AllowThousands 천 단위 구분 기호(,) 요소입니다.
NumberStyles.AllowCurrencySymbol $ 요소입니다.
NumberStyles.Currency 모든 요소. 매개 변수는 s 16진수 또는 지수 표기법으로 숫자를 나타낼 수 없습니다.
NumberStyles.Float s시작 또는 끝에 있는 ws 요소, 의 s시작 부분에 기호, 소수점(.) 기호입니다. 매개 변수는 s 지수 표기법을 사용할 수도 있습니다.
NumberStyles.Number ws, 기호, 천 단위 구분 기호(,) 및 소수점(.) 요소입니다.
NumberStyles.Any 를 제외한 s 모든 스타일은 16진수를 나타낼 수 없습니다.

플래그를 NumberStyles.AllowHexSpecifier 사용하는 s 경우 는 접두사 없이 16진수 값이어야 합니다. 예를 들어 "C9AF3"은 성공적으로 구문 분석되지만 "0xC9AF3"은 구문 분석하지 않습니다. 에 style 있을 수 있는 유일한 다른 플래그는 및 NumberStyles.AllowTrailingWhite입니다NumberStyles.AllowLeadingWhite. NumberStyles(열거형에는 공백 플래그를 모두 포함하는 복합 스타일 NumberStyles.HexNumber가 있습니다.)

provider 매개 변수는 메서드가 IFormatProvider 개체를 반환하는 CultureInfoNumberFormatInfo 개체 또는 개체 GetFormat 와 같은 구현입니다NumberFormatInfo. 개체는 NumberFormatInfo 형식 s에 대한 문화권별 정보를 제공합니다. 가 이 nullNumberFormatInfoprovider 현재 문화권의 개체가 사용됩니다.

추가 정보

적용 대상