다음을 통해 공유


Int64.TryParse 메서드

정의

숫자의 문자열 표현을 해당하는 64비트 부호 있는 정수로 변환합니다. 반환 값은 변환이 성공했는지 아니면 실패했는지를 나타냅니다.

오버로드

TryParse(String, IFormatProvider, Int64)

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

TryParse(ReadOnlySpan<Char>, Int64)

숫자의 범위 표현을 해당하는 64비트 부호 있는 정수로 변환합니다. 반환 값은 변환이 성공했는지 아니면 실패했는지를 나타냅니다.

TryParse(String, Int64)

숫자의 문자열 표현을 해당하는 64비트 부호 있는 정수로 변환합니다. 반환 값은 변환이 성공했는지 아니면 실패했는지를 나타냅니다.

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int64)

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

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int64)

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

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

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

TryParse(ReadOnlySpan<Byte>, Int64)

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

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

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

TryParse(String, NumberStyles, IFormatProvider, Int64)

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

TryParse(String, IFormatProvider, Int64)

Source:
Int64.cs
Source:
Int64.cs
Source:
Int64.cs

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

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

매개 변수

s
String

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

provider
IFormatProvider

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

result
Int64

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

반환

s 성공적으로 구문 분석되었는지 true. 그렇지 않으면 false.

적용 대상

TryParse(ReadOnlySpan<Char>, Int64)

Source:
Int64.cs
Source:
Int64.cs
Source:
Int64.cs

숫자의 범위 표현을 해당하는 64비트 부호 있는 정수로 변환합니다. 반환 값은 변환이 성공했는지 아니면 실패했는지를 나타냅니다.

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

매개 변수

s
ReadOnlySpan<Char>

변환할 숫자를 나타내는 문자가 들어 있는 범위입니다.

result
Int64

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

반환

s 성공적으로 변환되었는지 true. 그렇지 않으면 false.

적용 대상

TryParse(String, Int64)

Source:
Int64.cs
Source:
Int64.cs
Source:
Int64.cs

숫자의 문자열 표현을 해당하는 64비트 부호 있는 정수로 변환합니다. 반환 값은 변환이 성공했는지 아니면 실패했는지를 나타냅니다.

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

매개 변수

s
String

변환할 숫자를 포함하는 문자열입니다.

result
Int64

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

반환

s 성공적으로 변환되었는지 true. 그렇지 않으면 false.

예제

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

using System;

public class StringParsing
{
   public static void Main()
   {
      TryToParse(null);
      TryToParse("160519");
      TryToParse("9432.0");
      TryToParse("16,667");
      TryToParse("   -322   ");
      TryToParse("+4302");
      TryToParse("(100);");
      TryToParse("01FA");
   }

   private static void TryToParse(string value)
   {
      bool success = Int64.TryParse(value, out long number);
      if (success)
      {
         Console.WriteLine("Converted '{0}' to {1}.", value, number);
      }
      else
      {
         if (value == null) value = "";
         Console.WriteLine("Attempted conversion of '{0}' failed.", value);
      }
   }
}
// The example displays the following output to the console:
//       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.
open System

let tryToParse (value: string) =
    match Int64.TryParse value with
    | true, number ->
        printfn $"Converted '{value}' to {number}."
    | _ ->
        let value =
            if isNull value then 
                ""
            else
                value
        printfn $"Attempted conversion of '{value}' failed."

tryToParse null
tryToParse "160519"
tryToParse "9432.0"
tryToParse "16,667"
tryToParse "   -322   "
tryToParse "+4302"
tryToParse "(100);"
tryToParse "01FA"


// The example displays the following output to the console:
//       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.
Module StringParsing
   Public Sub Main()
      TryToParse(Nothing)
      TryToParse("160519")
      TryToParse("9432.0")
      TryToParse("16,667")
      TryToParse("   -322   ")
      TryToParse("+4302")
      TryToParse("(100)")
      TryToParse("01FA")
   End Sub
   
   Private Sub TryToParse(value As String)
      Dim number As Long
      Dim result As Boolean = Int64.TryParse(value, number)
      If result Then
         Console.WriteLine("Converted '{0}' to {1}.", value, number)
      Else
         If value Is Nothing Then value = "" 
         Console.WriteLine("Attempted conversion of '{0}' failed.", value)
      End If     
   End Sub
End Module
' The example displays the following output to the console:
'       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.

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

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

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

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

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

설명

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

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

[ws] [sign]digits[ws]

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

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

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

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

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

추가 정보

적용 대상

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int64)

Source:
Int64.cs
Source:
Int64.cs

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

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

매개 변수

utf8Text
ReadOnlySpan<Byte>

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

provider
IFormatProvider

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

result
Int64

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

반환

utf8Text 성공적으로 구문 분석되었는지 true. 그렇지 않으면 false.

적용 대상

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int64)

Source:
Int64.cs
Source:
Int64.cs
Source:
Int64.cs

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

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

매개 변수

s
ReadOnlySpan<Char>

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

provider
IFormatProvider

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

result
Int64

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

반환

s 성공적으로 구문 분석되었는지 true. 그렇지 않으면 false.

적용 대상

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

Source:
Int64.cs
Source:
Int64.cs

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

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

매개 변수

utf8Text
ReadOnlySpan<Byte>

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

style
NumberStyles

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

provider
IFormatProvider

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

result
Int64

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

반환

utf8Text 성공적으로 구문 분석되었는지 true. 그렇지 않으면 false.

적용 대상

TryParse(ReadOnlySpan<Byte>, Int64)

Source:
Int64.cs
Source:
Int64.cs

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

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

매개 변수

utf8Text
ReadOnlySpan<Byte>

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

result
Int64

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

반환

utf8Text 성공적으로 변환되었는지 true. 그렇지 않으면 false.

적용 대상

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

Source:
Int64.cs
Source:
Int64.cs
Source:
Int64.cs

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

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

매개 변수

s
ReadOnlySpan<Char>

변환할 숫자를 나타내는 문자가 들어 있는 범위입니다. 범위는 style지정한 스타일을 사용하여 해석됩니다.

style
NumberStyles

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

provider
IFormatProvider

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

result
Int64

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

반환

s 성공적으로 변환되었는지 true. 그렇지 않으면 false.

적용 대상

TryParse(String, NumberStyles, IFormatProvider, Int64)

Source:
Int64.cs
Source:
Int64.cs
Source:
Int64.cs

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

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

매개 변수

s
String

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

style
NumberStyles

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

provider
IFormatProvider

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

result
Int64

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

반환

s 성공적으로 변환되었는지 true. 그렇지 않으면 false.

예외

style NumberStyles 값이 아닙니다.

-또는-

style AllowHexSpecifier 값과 HexNumber 값의 조합이 아닙니다.

예제

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

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 = Int64.TryParse(stringToConvert, styles,
                                   provider, out long 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 Int64.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 Long
      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 = Int64.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 메서드는 변환이 실패할 경우 TryParse 메서드가 예외를 throw하지 않는다는 점을 제외하고 Parse 메서드와 같습니다. s 유효하지 않고 성공적으로 구문 분석할 수 없는 경우 예외 처리를 사용하여 FormatException 테스트할 필요가 없습니다.

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

[ws] [$] [sign] [digits,]digits[.fractional_digits][e[sign]exponential_digits][ws]

또는 style 매개 변수에 NumberStyles.AllowHexSpecifier포함되어 있는 경우:

[ws]hexdigits[ws]

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

요소 묘사
ws 선택적 공백입니다. style NumberStyles.AllowLeadingWhite 플래그를 포함하는 경우 s 시작 부분에 공백을 표시하거나 styleNumberStyles.AllowTrailingWhite 플래그를 포함하는 경우 s 끝에 나타날 수 있습니다.
$ 문화권별 통화 기호입니다. 문자열의 위치는 provider 매개 변수의 GetFormat 메서드에서 반환된 NumberFormatInfo 개체의 CurrencyPositivePattern 속성에 의해 정의됩니다. style NumberStyles.AllowCurrencySymbol 플래그를 포함하는 경우 통화 기호가 s 나타날 수 있습니다.
기호 선택적 기호입니다. style NumberStyles.AllowLeadingSign 또는 NumberStyles.AllowTrailingSign 플래그를 포함하는 경우 기호 기호가 s 나타날 수 있습니다.
숫자

fractional_digits

exponential_digits
0에서 9까지의 숫자 시퀀스입니다. fractional_digits경우 숫자 0만 유효합니다.
, 문화권별 천 단위 구분 기호입니다. style NumberStyles.AllowThousands 플래그를 포함하는 경우 provider 지정된 문화권의 천 단위 구분 기호가 s 나타날 수 있습니다.
. 문화권별 소수점 기호입니다. style NumberStyles.AllowDecimalPoint 플래그를 포함하는 경우 provider 지정된 문화권의 소수점 기호가 s 나타날 수 있습니다.
e 값이 지수 표기법으로 표시됨을 나타내는 'e' 또는 'E' 문자입니다. s 매개 변수는 styleNumberStyles.AllowExponent 플래그를 포함하는 경우 지수 표기법으로 숫자를 나타낼 수 있습니다.
16진수 0부터 f까지의 16진수 숫자 또는 0부터 F까지의 시퀀스입니다.

메모

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

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

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

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

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

추가 정보

적용 대상