다음을 통해 공유


UInt16.TryParse 메서드

정의

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

오버로드

TryParse(ReadOnlySpan<Byte>, IFormatProvider, UInt16)

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

TryParse(ReadOnlySpan<Char>, UInt16)

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

TryParse(String, UInt16)

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

TryParse(ReadOnlySpan<Char>, IFormatProvider, UInt16)

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

TryParse(String, IFormatProvider, UInt16)

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

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

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

TryParse(ReadOnlySpan<Byte>, UInt16)

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

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

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

TryParse(String, NumberStyles, IFormatProvider, UInt16)

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

TryParse(ReadOnlySpan<Byte>, IFormatProvider, UInt16)

Source:
UInt16.cs
Source:
UInt16.cs

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

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

매개 변수

utf8Text
ReadOnlySpan<Byte>

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

provider
IFormatProvider

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

result
UInt16

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

반환

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

적용 대상

TryParse(ReadOnlySpan<Char>, UInt16)

Source:
UInt16.cs
Source:
UInt16.cs
Source:
UInt16.cs

중요

이 API는 CLS 규격이 아닙니다.

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

public:
 static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] System::UInt16 % result);
public static bool TryParse (ReadOnlySpan<char> s, out ushort result);
[System.CLSCompliant(false)]
public static bool TryParse (ReadOnlySpan<char> s, out ushort result);
static member TryParse : ReadOnlySpan<char> * uint16 -> bool
[<System.CLSCompliant(false)>]
static member TryParse : ReadOnlySpan<char> * uint16 -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As UShort) As Boolean

매개 변수

s
ReadOnlySpan<Char>

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

result
UInt16

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

반환

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

특성

적용 대상

TryParse(String, UInt16)

Source:
UInt16.cs
Source:
UInt16.cs
Source:
UInt16.cs

중요

이 API는 CLS 규격이 아닙니다.

CLS 대체 규격
System.Int32.TryParse(String, Int32)

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

public:
 static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] System::UInt16 % result);
[System.CLSCompliant(false)]
public static bool TryParse (string s, out ushort result);
public static bool TryParse (string? s, out ushort result);
[System.CLSCompliant(false)]
public static bool TryParse (string? s, out ushort result);
[<System.CLSCompliant(false)>]
static member TryParse : string * uint16 -> bool
static member TryParse : string * uint16 -> bool
Public Shared Function TryParse (s As String, ByRef result As UShort) As Boolean

매개 변수

s
String

변환할 숫자를 나타내는 문자열입니다.

result
UInt16

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

반환

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

특성

예제

다음 예제에서는 문자열 배열의 각 요소에 대해 TryParse(String, UInt16) 메서드를 한 번 호출합니다.

string[] numericStrings = { "1293.8", "+1671.7", "28347.",  
                            "   33113684  ", "(0)", "-0", "-1", 
                            "+1293617", "18-", "119870", "31,024", 
                            "  3127094 ", "00700000" };
uint number;
foreach (string numericString in numericStrings)
{
   if (UInt32.TryParse(numericString, out number)) 
      Console.WriteLine("Converted '{0}' to {1}.", numericString, number);
   else
      Console.WriteLine("Cannot convert '{0}' to a UInt32.", numericString);
}
// The example displays the following output:
//       Cannot convert '1293.8' to a UInt32.
//       Cannot convert '+1671.7' to a UInt32.
//       Cannot convert '28347.' to a UInt32.
//       Converted '   33113684  ' to 33113684.
//       Cannot convert '(0)' to a UInt32.
//       Converted '-0' to 0.
//       Cannot convert '-1' to a UInt32.
//       Converted '+1293617' to 1293617.
//       Cannot convert '18-' to a UInt32.
//       Converted '119870' to 119870.
//       Cannot convert '31,024' to a UInt32.
//       Converted '  3127094 ' to 3127094.
//       Converted '0070000' to 70000.
let numericStrings = 
    [| "1293.8"; "+1671.7"; "28347."
       "   33113684  "; "(0)"; "-0"; "-1" 
       "+1293617"; "18-"; "119870"; "31,024" 
       "  3127094 "; "00700000" |]

for numericString in numericStrings do
    match UInt32.TryParse numericString with
    | true, number ->
        printfn $"Converted '{numericString}' to {number}."
    | _ ->
        printfn $"Cannot convert '{numericString}' to a UInt32."
// The example displays the following output:
//       Cannot convert '1293.8' to a UInt32.
//       Cannot convert '+1671.7' to a UInt32.
//       Cannot convert '28347.' to a UInt32.
//       Converted '   33113684  ' to 33113684.
//       Cannot convert '(0)' to a UInt32.
//       Converted '-0' to 0.
//       Cannot convert '-1' to a UInt32.
//       Converted '+1293617' to 1293617.
//       Cannot convert '18-' to a UInt32.
//       Converted '119870' to 119870.
//       Cannot convert '31,024' to a UInt32.
//       Converted '  3127094 ' to 3127094.
//       Converted '0070000' to 70000.
Dim numericStrings() As String = {"1293.8", "+1671.7", "28347.", 
                                  "   33113684  ", "(0)", "-0", "-1",
                                  "+1293617", "18-", "119870", 
                                  "31,024", "  3127094 ", "0070000" }
Dim number As UInteger
For Each numericString As String In numericStrings
   If UInt32.TryParse(numericString, number) Then
      Console.WriteLine("Converted '{0}' to {1}.", numericString, number)
   Else
      Console.WriteLine("Cannot convert '{0}' to a UInt32.", numericString)
   End If      
Next
' The example displays the following output:
'       Cannot convert '1293.8' to a UInt32.
'       Cannot convert '+1671.7' to a UInt32.
'       Cannot convert '28347.' to a UInt32.
'       Converted '   33113684  ' to 33113684.
'       Cannot convert '(0)' to a UInt32.
'       Converted '-0' to 0.
'       Cannot convert '-1' to a UInt32.
'       Converted '+1293617' to 1293617.
'       Cannot convert '18-' to a UInt32.
'       Converted '119870' to 119870.
'       Cannot convert '31,024' to a UInt32.
'       Converted '  3127094 ' to 3127094.
'       Converted '0070000' to 70000.

설명

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

s 매개 변수는 다음 형식의 10진수 문자열 표현이어야 합니다.

[ws] [sign]digits[ws]

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

요소 묘사
ws 선택적 공백입니다.
기호 선택적 기호입니다. 유효한 부호 문자는 현재 문화권의 NumberFormatInfo.NegativeSignNumberFormatInfo.PositiveSign 속성에 의해 결정됩니다.
숫자 0에서 9 사이의 소수 자릿수 시퀀스입니다.

메모

s 매개 변수로 지정된 문자열에는 그룹 구분 기호 또는 소수 구분 기호를 포함할 수 없으며 소수 부분을 가질 수 없습니다.

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

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

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

추가 정보

적용 대상

TryParse(ReadOnlySpan<Char>, IFormatProvider, UInt16)

Source:
UInt16.cs
Source:
UInt16.cs
Source:
UInt16.cs

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

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

매개 변수

s
ReadOnlySpan<Char>

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

provider
IFormatProvider

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

result
UInt16

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

반환

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

적용 대상

TryParse(String, IFormatProvider, UInt16)

Source:
UInt16.cs
Source:
UInt16.cs
Source:
UInt16.cs

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

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

매개 변수

s
String

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

provider
IFormatProvider

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

result
UInt16

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

반환

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

적용 대상

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

Source:
UInt16.cs
Source:
UInt16.cs

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

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

매개 변수

utf8Text
ReadOnlySpan<Byte>

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

style
NumberStyles

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

provider
IFormatProvider

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

result
UInt16

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

반환

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

적용 대상

TryParse(ReadOnlySpan<Byte>, UInt16)

Source:
UInt16.cs
Source:
UInt16.cs

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

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

매개 변수

utf8Text
ReadOnlySpan<Byte>

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

result
UInt16

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

반환

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

적용 대상

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

Source:
UInt16.cs
Source:
UInt16.cs
Source:
UInt16.cs

중요

이 API는 CLS 규격이 아닙니다.

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

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

매개 변수

s
ReadOnlySpan<Char>

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

style
NumberStyles

허용되는 s형식을 나타내는 열거형 값의 비트 조합입니다. 지정하는 일반적인 값은 Integer.

provider
IFormatProvider

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

result
UInt16

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

반환

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

특성

적용 대상

TryParse(String, NumberStyles, IFormatProvider, UInt16)

Source:
UInt16.cs
Source:
UInt16.cs
Source:
UInt16.cs

중요

이 API는 CLS 규격이 아닙니다.

CLS 대체 규격
System.Int32.TryParse(String, Int32)

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

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

매개 변수

s
String

변환할 숫자를 나타내는 문자열입니다. 문자열은 style 매개 변수로 지정된 스타일을 사용하여 해석됩니다.

style
NumberStyles

허용되는 s형식을 나타내는 열거형 값의 비트 조합입니다. 지정하는 일반적인 값은 Integer.

provider
IFormatProvider

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

result
UInt16

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

반환

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

특성

예외

style NumberStyles 값이 아닙니다.

-또는-

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

예제

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

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string numericString;
      NumberStyles styles;
      
      numericString = "10603";
      styles = NumberStyles.Integer;
      CallTryParse(numericString, styles);
      
      numericString = "-10603";
      styles = NumberStyles.None;
      CallTryParse(numericString, styles);
      
      numericString = "29103.00";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);
      
      numericString = "10345.72";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "2210E-01";
      styles = NumberStyles.Integer | NumberStyles.AllowExponent;
      CallTryParse(numericString, styles); 
      
      numericString = "9112E-01";
      CallTryParse(numericString, styles);
          
      numericString = "312E01";
      CallTryParse(numericString, styles); 
      
      numericString = "FFC8";
      CallTryParse(numericString, NumberStyles.HexNumber);
      
      numericString = "0x8F8C";
      CallTryParse(numericString, NumberStyles.HexNumber);
   }
   
   private static void CallTryParse(string stringToConvert, NumberStyles styles)
   {
      ushort number;
      bool result = UInt16.TryParse(stringToConvert, styles, 
                                   CultureInfo.InvariantCulture, out number);
      if (result)
         Console.WriteLine($"Converted '{stringToConvert}' to {number}.");
      else
         Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed.");
   }
}
// The example displays the following output:
//       Converted '10603' to 10603.
//       Attempted conversion of '-10603' failed.
//       Converted '29103.00' to 29103.
//       Attempted conversion of '10345.72' failed.
//       Converted '2210E-01' to 221.
//       Attempted conversion of '9112E-01' failed.
//       Converted '312E01' to 3120.
//       Converted 'FFC8' to 65480.
//       Attempted conversion of '0x8F8C' failed.
open System
open System.Globalization

let callTryParse (stringToConvert: string) (styles: NumberStyles) =
    match UInt16.TryParse(stringToConvert, styles, CultureInfo.InvariantCulture) with
    | true, number ->
        printfn $"Converted '{stringToConvert}' to {number}."
    | _ -> 
        printfn $"Attempted conversion of '{stringToConvert}' failed."

do
    let numericString = "10603"
    let styles = NumberStyles.Integer
    callTryParse numericString styles
    
    let numericString = "-10603"
    let styles = NumberStyles.None
    callTryParse numericString styles
    
    let numericString = "29103.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 = "2210E-01"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowExponent
    callTryParse numericString styles
    
    let numericString = "9112E-01"
    callTryParse numericString styles
        
    let numericString = "312E01"
    callTryParse numericString styles
    
    let numericString = "FFC8"
    callTryParse numericString NumberStyles.HexNumber
    
    let numericString = "0x8F8C"
    callTryParse numericString NumberStyles.HexNumber
// The example displays the following output:
//       Converted '10603' to 10603.
//       Attempted conversion of '-10603' failed.
//       Converted '29103.00' to 29103.
//       Attempted conversion of '10345.72' failed.
//       Converted '2210E-01' to 221.
//       Attempted conversion of '9112E-01' failed.
//       Converted '312E01' to 3120.
//       Converted 'FFC8' to 65480.
//       Attempted conversion of '0x8F8C' failed.
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim numericString As String
      Dim styles As NumberStyles
      
      numericString = "10603"
      styles = NumberStyles.Integer
      CallTryParse(numericString, styles)
      
      numericString = "-10603"
      styles = NumberStyles.None
      CallTryParse(numericString, styles)
      
      numericString = "29103.00"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)
      
      numericString = "10345.72"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)

      numericString = "2210E-01"
      styles = NumberStyles.Integer Or NumberStyles.AllowExponent
      CallTryParse(numericString, styles) 
      
      numericString = "9112E-01"
      CallTryParse(numericString, styles)
          
      numericString = "312E01"
      CallTryParse(numericString, styles) 
      
      numericString = "FFC8"
      CallTryParse(numericString, NumberStyles.HexNumber)
      
      numericString = "0x8F8C"
      CallTryParse(numericString, NumberStyles.HexNumber)
   End Sub
   
   Private Sub CallTryParse(stringToConvert As String, styles AS NumberStyles)
      Dim number As UShort
      Dim result As Boolean = UInt16.TryParse(stringToConvert, styles, _
                                              CultureInfo.InvariantCulture, 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 '10603' to 10603.
'       Attempted conversion of '-10603' failed.
'       Converted '29103.00' to 29103.
'       Attempted conversion of '10345.72' failed.
'       Converted '2210E-01' to 221.
'       Attempted conversion of '9112E-01' failed.
'       Converted '312E01' to 3120.
'       Converted 'FFC8' to 65480.
'       Attempted conversion of '0x8F8C' failed.

설명

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

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

[ws] [$] [sign] [숫자,]숫자[.fractional_digits][E[기호]exponential_digits][ws]

대괄호([ 및 ])의 항목은 선택 사항입니다. 또는 style 매개 변수에 AllowHexSpecifier포함된 경우 s 매개 변수에는 다음 요소가 포함될 수 있습니다.

[ws]hexdigits[ws]

다음 표에서는 각 요소에 대해 설명합니다.

ws 선택적 공백입니다. style NumberStyles.AllowLeadingWhite 플래그를 포함하는 경우 s 시작 부분에 공백을 표시하거나 styleNumberStyles.AllowTrailingWhite 플래그를 포함하는 경우 s 끝에 나타날 수 있습니다.

$ 문화권별 통화 기호입니다. 문자열의 위치는 provider 매개 변수의 GetFormat 메서드에서 반환된 NumberFormatInfo 개체의 CurrencyPositivePattern 속성에 의해 정의됩니다. style NumberStyles.AllowCurrencySymbol 플래그를 포함하는 경우 통화 기호가 s 나타날 수 있습니다.

기호 선택적 기호입니다. style NumberStyles.AllowLeadingSign 플래그를 포함하는 경우 s 시작 부분에 표시할 수 있으며, styleNumberStyles.AllowTrailingSign 플래그를 포함하는 경우 s 끝에 표시할 수 있습니다. style NumberStyles.AllowParentheses 플래그를 포함하는 경우 s 괄호를 사용하여 음수 값을 나타낼 수 있습니다. 그러나 음수 기호가 있는 경우 s 구문 분석 작업이 성공하기 위한 값 0만 나타낼 수 있습니다.

숫자 0부터 9까지의 숫자 시퀀스입니다.

, 문화권별 그룹 구분 기호입니다. style NumberStyles.AllowThousands 플래그를 포함하는 경우 provider 지정된 문화권의 그룹 구분 기호가 s 나타날 수 있습니다.

. 문화권별 소수점 기호입니다. style NumberStyles.AllowDecimalPoint 플래그를 포함하는 경우 provider 지정된 문화권의 소수점 기호가 s 나타날 수 있습니다.

fractional_digits 숫자 0이 하나 이상 발생합니다. 소수 자릿수는 styleNumberStyles.AllowDecimalPoint 플래그를 포함하는 경우에만 s 나타날 수 있습니다.

E 값이 지수(과학적) 표기법으로 표현됨을 나타내는 "e" 또는 "E" 문자입니다. s 매개 변수는 styleNumberStyles.AllowExponent 플래그를 포함하는 경우 지수 표기법으로 숫자를 나타낼 수 있습니다.

exponential_digits 0에서 9까지의 숫자 시퀀스입니다. s 매개 변수는 styleNumberStyles.AllowExponent 플래그를 포함하는 경우 지수 표기법으로 숫자를 나타낼 수 있습니다.

16진수 0부터 f까지 또는 0부터 F까지의 16진수 시퀀스입니다.

메모

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

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

비 복합 NumberStyles 숫자 외에도 값에 허용되는 요소
None 10진수에만 해당합니다.
AllowDecimalPoint 소수점(.) 및 fractional_digits 요소입니다. 그러나 fractional_digits 하나 이상의 0자리 숫자로만 구성되거나 메서드가 false반환해야 합니다.
AllowExponent exponential_digits함께 지수 표기법을 나타내는 "e" 또는 "E" 문자입니다. s 지수 표기법의 숫자를 나타내는 경우 0이 아닌 소수 구성 요소를 가질 수 없습니다.
AllowLeadingWhite s시작할 때 ws 요소입니다.
AllowTrailingWhite s끝에 있는 ws 요소입니다.
AllowLeadingSign 숫자앞에 있는 기호 요소입니다.
AllowTrailingSign 숫자기호 요소입니다.
AllowParentheses 기호는 0 숫자 값을 묶는 괄호 형식의 요소.
AllowThousands 그룹 구분 기호(,) 요소입니다.
AllowCurrencySymbol currency($) 요소입니다.
Currency 모든 요소. 그러나 s 16진수 또는 지수 표기법의 숫자를 나타낼 수 없습니다.
Float 시작 또는 끝에 있는 ws 요소, 시작 시 기호 및 소수점(.) 기호입니다. s 매개 변수는 지수 표기법을 사용할 수도 있습니다.
Number ws, 기호, 그룹 구분 기호(,), 소수점(.) 요소입니다.
Any 모든 요소. 그러나 s 16진수를 나타낼 수 없습니다.

NumberStyles.AllowHexSpecifier 플래그를 사용하는 경우 s 16진수 값이어야 합니다. 유효한 16진수는 0~9, a-f 및 A-F입니다. "0x"와 같은 접두사는 지원되지 않으며 구문 분석 작업이 실패합니다. style 있을 수 있는 유일한 다른 플래그는 NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhite. (NumberStyles 열거형에는 공백 플래그를 모두 포함하는 복합 스타일(HexNumber)이 있습니다.

메모

s 16진수의 문자열 표현인 경우 16진수로 구분하는 장식(예: 0x 또는 &h)이 앞에 올 수 없습니다. 이렇게 하면 변환이 실패합니다.

provider 매개 변수는 IFormatProvider 구현입니다. 해당 GetFormat 메서드는 s형식에 대한 문화권별 정보를 제공하는 NumberFormatInfo 개체를 반환합니다. provider 매개 변수는 다음 중 하나일 수 있습니다.

  • 서식 정보를 제공하는 문화권을 나타내는 CultureInfo 개체입니다. 해당 GetFormat 메서드는 해당 문화권에 대한 숫자 서식 정보를 제공하는 NumberFormatInfo 개체를 반환합니다.

  • 숫자 서식 정보를 제공하는 NumberFormatInfo 개체입니다. (GetFormat 구현은 그 자체를 반환합니다.)

  • IFormatProvider구현하는 사용자 지정 개체입니다. 해당 GetFormat 메서드는 서식 정보를 제공하는 NumberFormatInfo 개체를 인스턴스화하고 반환합니다.

provider null경우 현재 문화권의 NumberFormatInfo 개체가 사용됩니다.

추가 정보

적용 대상