UInt16.Parse Metoda

Definicja

Konwertuje ciąg reprezentujący liczbę na odpowiadającą mu 16-bitową liczbę całkowitą bez znaku.

Przeciążenia

Parse(String, NumberStyles, IFormatProvider)

Konwertuje reprezentację ciągu liczby w określonym stylu i formacie specyficznym dla kultury na odpowiednik 16-bitowej liczby całkowitej bez znaku.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Konwertuje reprezentację zakresu liczby w określonym stylu i formacie specyficznym dla kultury na odpowiednik 16-bitowej liczby całkowitej bez znaku.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Analizuje zakres znaków UTF-8 w wartości.

Parse(String, IFormatProvider)

Konwertuje reprezentację ciągu liczby w określonym formacie specyficznym dla kultury na odpowiednik 16-bitowej liczby całkowitej bez znaku.

Parse(String, NumberStyles)

Konwertuje reprezentację ciągu liczby w określonym stylu na odpowiednik 16-bitowej liczby całkowitej bez znaku.

Ta metoda nie jest zgodna ze specyfikacją CLS. Alternatywą zgodną ze specyfikacją CLS jest Parse(String, NumberStyles).

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analizuje zakres znaków w wartości.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Analizuje zakres znaków UTF-8 w wartości.

Parse(String)

Konwertuje ciąg reprezentujący liczbę na odpowiadającą mu 16-bitową liczbę całkowitą bez znaku.

Parse(String, NumberStyles, IFormatProvider)

Źródło:
UInt16.cs
Źródło:
UInt16.cs
Źródło:
UInt16.cs

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Alternatywa zgodna ze specyfikacją CLS
System.Int32.Parse(String)

Konwertuje reprezentację ciągu liczby w określonym stylu i formacie specyficznym dla kultury na odpowiednik 16-bitowej liczby całkowitej bez znaku.

public:
 static System::UInt16 Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
 static System::UInt16 Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<System::UInt16>::Parse;
[System.CLSCompliant(false)]
public static ushort Parse (string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static ushort Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static ushort Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> uint16
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> uint16
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As UShort

Parametry

s
String

Ciąg reprezentujący liczbę, którą należy przekształcić. Ciąg jest interpretowany przy użyciu stylu określonego style przez parametr .

style
NumberStyles

Bitowa kombinacja wartości wyliczenia, które wskazują elementy stylu, które mogą być obecne w .s Typową wartością do określenia jest Integer.

provider
IFormatProvider

Obiekt, który dostarcza informacje o formatowaniu specyficznym dla kultury.s

Zwraca

16-bitowa liczba całkowita bez znaku równoważna liczbie określonej w elemencie s.

Implementuje

Atrybuty

Wyjątki

style nie jest wartością NumberStyles .

-lub-

style nie jest kombinacją AllowHexSpecifier wartości i HexNumber .

s nie jest w formacie zgodnym z parametrem style.

s reprezentuje liczbę mniejszą niż UInt16.MinValue lub większą niż UInt16.MaxValue.

-lub-

s zawiera cyfry niezerowe, ułamkowe.

Przykłady

W poniższym przykładzie użyto Parse(String, NumberStyles, IFormatProvider) metody , aby przekonwertować różne reprezentacje ciągów liczb na 16-bitowe niepodpisane wartości całkowite.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] cultureNames = { "en-US", "fr-FR" };
      NumberStyles[] styles= { NumberStyles.Integer, 
                               NumberStyles.Integer | NumberStyles.AllowDecimalPoint };
      string[] values = { "1702", "+1702.0", "+1702,0", "-1032.00",
                          "-1032,00", "1045.1", "1045,1" };
      
      // Parse strings using each culture
      foreach (string cultureName in cultureNames)
      {
         CultureInfo ci = new CultureInfo(cultureName);
         Console.WriteLine("Parsing strings using the {0} culture", 
                           ci.DisplayName);
         // Use each style.
         foreach (NumberStyles style in styles)
         {
            Console.WriteLine("   Style: {0}", style.ToString());
            // Parse each numeric string.
            foreach (string value in values)
            {
               try {
                  Console.WriteLine("      Converted '{0}' to {1}.", value, 
                                    UInt16.Parse(value, style, ci));
               }                                    
               catch (FormatException) {
                  Console.WriteLine("      Unable to parse '{0}'.", value);   
               }
               catch (OverflowException) {
                  Console.WriteLine("      '{0}' is out of range of the UInt16 type.", 
                                    value);
               }
            }
         }
      }   
   }
}
// The example displays the following output:
//       Parsing strings using the English (United States) culture
//          Style: Integer
//             Converted '1702' to 1702.
//             Unable to parse '+1702.0'.
//             Unable to parse '+1702,0'.
//             Unable to parse '-1032.00'.
//             Unable to parse '-1032,00'.
//             Unable to parse '1045.1'.
//             Unable to parse '1045,1'.
//          Style: Integer, AllowDecimalPoint
//             Converted '1702' to 1702.
//             Converted '+1702.0' to 1702.
//             Unable to parse '+1702,0'.
//             '-1032.00' is out of range of the UInt16 type.
//             Unable to parse '-1032,00'.
//             '1045.1' is out of range of the UInt16 type.
//             Unable to parse '1045,1'.
//       Parsing strings using the French (France) culture
//          Style: Integer
//             Converted '1702' to 1702.
//             Unable to parse '+1702.0'.
//             Unable to parse '+1702,0'.
//             Unable to parse '-1032.00'.
//             Unable to parse '-1032,00'.
//             Unable to parse '1045.1'.
//             Unable to parse '1045,1'.
//          Style: Integer, AllowDecimalPoint
//             Converted '1702' to 1702.
//             Unable to parse '+1702.0'.
//             Converted '+1702,0' to 1702.
//             Unable to parse '-1032.00'.
//             '-1032,00' is out of range of the UInt16 type.
//             Unable to parse '1045.1'.
//             '1045,1' is out of range of the UInt16 type.
open System
open System.Globalization

let cultureNames = [| "en-US"; "fr-FR" |]
let styles = 
    [| NumberStyles.Integer; NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint |]
let values =
    [| "1702"; "+1702.0"; "+1702,0"; "-1032.00"; "-1032,00"; "1045.1"; "1045,1" |]

// Parse strings using each culture
for cultureName in cultureNames do
    let ci = CultureInfo cultureName
    printfn $"Parsing strings using the {ci.DisplayName} culture"
    // Use each style.
    for style in styles do
        printfn $"   Style: {style}"
        // Parse each numeric string.
        for value in values do
            try
                printfn $"      Converted '{value}' to {UInt16.Parse(value, style, ci)}."
            with
            | :? FormatException ->
                printfn $"      Unable to parse '{value}'."
            | :? OverflowException ->
                printfn $"      '{value}' is out of range of the UInt16 type."
// The example displays the following output:
//       Parsing strings using the English (United States) culture
//          Style: Integer
//             Converted '1702' to 1702.
//             Unable to parse '+1702.0'.
//             Unable to parse '+1702,0'.
//             Unable to parse '-1032.00'.
//             Unable to parse '-1032,00'.
//             Unable to parse '1045.1'.
//             Unable to parse '1045,1'.
//          Style: Integer, AllowDecimalPoint
//             Converted '1702' to 1702.
//             Converted '+1702.0' to 1702.
//             Unable to parse '+1702,0'.
//             '-1032.00' is out of range of the UInt16 type.
//             Unable to parse '-1032,00'.
//             '1045.1' is out of range of the UInt16 type.
//             Unable to parse '1045,1'.
//       Parsing strings using the French (France) culture
//          Style: Integer
//             Converted '1702' to 1702.
//             Unable to parse '+1702.0'.
//             Unable to parse '+1702,0'.
//             Unable to parse '-1032.00'.
//             Unable to parse '-1032,00'.
//             Unable to parse '1045.1'.
//             Unable to parse '1045,1'.
//          Style: Integer, AllowDecimalPoint
//             Converted '1702' to 1702.
//             Unable to parse '+1702.0'.
//             Converted '+1702,0' to 1702.
//             Unable to parse '-1032.00'.
//             '-1032,00' is out of range of the UInt16 type.
//             Unable to parse '1045.1'.
//             '1045,1' is out of range of the UInt16 type.
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "en-US", "fr-FR" }
      Dim styles() As NumberStyles = { NumberStyles.Integer, _
                                       NumberStyles.Integer Or NumberStyles.AllowDecimalPoint }
      Dim values() As String = { "1702", "+1702.0", "+1702,0", "-1032.00", _
                                 "-1032,00", "1045.1", "1045,1" }
      
      ' Parse strings using each culture
      For Each cultureName As String In cultureNames
         Dim ci As New CultureInfo(cultureName)
         Console.WriteLine("Parsing strings using the {0} culture", ci.DisplayName)
         ' Use each style.
         For Each style As NumberStyles In styles
            Console.WriteLine("   Style: {0}", style.ToString())
            ' Parse each numeric string.
            For Each value As String In values
               Try
                  Console.WriteLine("      Converted '{0}' to {1}.", value, _
                                    UInt16.Parse(value, style, ci))
               Catch e As FormatException
                  Console.WriteLine("      Unable to parse '{0}'.", value)   
               Catch e As OverflowException
                  Console.WriteLine("      '{0}' is out of range of the UInt16 type.", _
                                    value)         
               End Try
            Next
         Next
      Next                                    
   End Sub
End Module
' The example displays the following output:
'       Parsing strings using the English (United States) culture
'          Style: Integer
'             Converted '1702' to 1702.
'             Unable to parse '+1702.0'.
'             Unable to parse '+1702,0'.
'             Unable to parse '-1032.00'.
'             Unable to parse '-1032,00'.
'             Unable to parse '1045.1'.
'             Unable to parse '1045,1'.
'          Style: Integer, AllowDecimalPoint
'             Converted '1702' to 1702.
'             Converted '+1702.0' to 1702.
'             Unable to parse '+1702,0'.
'             '-1032.00' is out of range of the UInt16 type.
'             Unable to parse '-1032,00'.
'             '1045.1' is out of range of the UInt16 type.
'             Unable to parse '1045,1'.
'       Parsing strings using the French (France) culture
'          Style: Integer
'             Converted '1702' to 1702.
'             Unable to parse '+1702.0'.
'             Unable to parse '+1702,0'.
'             Unable to parse '-1032.00'.
'             Unable to parse '-1032,00'.
'             Unable to parse '1045.1'.
'             Unable to parse '1045,1'.
'          Style: Integer, AllowDecimalPoint
'             Converted '1702' to 1702.
'             Unable to parse '+1702.0'.
'             Converted '+1702,0' to 1702.
'             Unable to parse '-1032.00'.
'             '-1032,00' is out of range of the UInt16 type.
'             Unable to parse '1045.1'.
'             '1045,1' is out of range of the UInt16 type.

Uwagi

Parametr style definiuje elementy stylu (takie jak biały znak lub symbol znaku dodatniego lub ujemnego), które są dozwolone w parametrze s dla operacji analizy powodzenia. Musi to być kombinacja flag bitowych z NumberStyles wyliczenia.

W zależności od wartości styleparametr może s zawierać następujące elementy:

[ws] [$][znak]cyfry[.fractional_digits][E[znak]exponential_digits][ws]

Elementy w nawiasach kwadratowych ([ i ]) są opcjonalne. Jeśli style parametr zawiera NumberStyles.AllowHexSpecifierparametr , s może zawierać następujące elementy:

[ws] hexdigits[ws]

W tabeli poniżej opisano każdy element.

Element Opis
Ws Opcjonalny odstęp. Białe znaki mogą pojawić się na początku s , jeśli style zawiera flagę NumberStyles.AllowLeadingWhite , i może pojawić się na końcu s , jeśli style zawiera flagę NumberStyles.AllowTrailingWhite .
$ Symbol waluty specyficzny dla kultury. Jego pozycja w ciągu jest definiowana przez CurrencyPositivePattern właściwość NumberFormatInfo obiektu, który jest zwracany przez GetFormat metodę parametru provider . Symbol waluty może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowCurrencySymbol .
sign Opcjonalny znak. (Metoda zgłasza OverflowException wyjątek if s zawiera znak ujemny i reprezentuje liczbę niezerową). Znak może pojawić się na początku s , jeśli style zawiera flagę NumberStyles.AllowLeadingSign i może pojawić się na końcu s , jeśli style zawiera flagę NumberStyles.AllowTrailingSign . Nawiasy mogą służyć s do wskazywania wartości ujemnej, jeśli style zawiera flagę NumberStyles.AllowParentheses .
Cyfr Sekwencja cyfr od 0 do 9.
. Symbol dziesiętny specyficzny dla kultury. Symbol punktu dziesiętnego bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowDecimalPoint .
fractional_digits Co najmniej jedno wystąpienie cyfry 0–9, jeśli style zawiera flagę NumberStyles.AllowExponent lub co najmniej jedno wystąpienie cyfry 0, jeśli nie. Cyfry ułamkowe mogą być wyświetlane tylko wtedy s , gdy style zawiera flagę NumberStyles.AllowDecimalPoint .
E Znak „e” lub „E”, który wskazuje, że wartość jest reprezentowana w zapisie wykładniczym (naukowym). Parametr s może reprezentować liczbę w notacji wykładniczej, jeśli style zawiera flagę NumberStyles.AllowExponent .
exponential_digits Sekwencja cyfr od 0 do 9. Parametr s może reprezentować liczbę w notacji wykładniczej, jeśli style zawiera flagę NumberStyles.AllowExponent .
hexdigits Sekwencja cyfr szesnastkowych od 0 do f lub od 0 do F.

Uwaga

Wszystkie znaki NUL zakończenia (U+0000) w s obiekcie są ignorowane przez operację analizowania, niezależnie od wartości argumentu style .

Ciąg z cyframi dziesiętnymi (odpowiadający NumberStyles.None stylowi) zawsze jest analizowanych pomyślnie. Większość pozostałych NumberStyles elementów członkowskich kontroluje, które mogą być obecne, ale nie muszą być obecne, w tym ciągu wejściowym. W poniższej tabeli przedstawiono, jak poszczególne NumberStyles elementy członkowskie wpływają na elementy, które mogą być obecne w programie s.

Wartości nieskładne NumberStyles Elementy dozwolone oprócz s cyfr
NumberStyles.None Tylko cyfry dziesiętne.
NumberStyles.AllowDecimalPoint Liczba dziesiętna (.) i fractional_digits elementów. Jeśli jednak styl nie zawiera flagi NumberStyles.AllowExponent , fractional_digits musi składać się tylko z jednej lub kilku cyfr; w przeciwnym razie OverflowException jest zgłaszana wartość .
NumberStyles.AllowExponent Znak "e" lub "E", który wskazuje notację wykładniczą, wraz z exponential_digits.
NumberStyles.AllowLeadingWhite Element ws na początku elementu s.
NumberStyles.AllowTrailingWhite Element ws na końcu elementu s.
NumberStyles.AllowLeadingSign Znak przed cyframi.
NumberStyles.AllowTrailingSign Znak po cyfrach.
NumberStyles.AllowParentheses Nawiasy przed cyframi i po, aby wskazać wartość ujemną.
NumberStyles.AllowThousands Element separatora grup (,).
NumberStyles.AllowCurrencySymbol Element waluty ($).

Jeśli flaga NumberStyles.AllowHexSpecifier jest używana, s musi być wartością szesnastkową. Prawidłowe cyfry szesnastkowe to od 0 do 9, od f i od A do F. Prefiks, taki jak "0x", nie jest obsługiwany i powoduje niepowodzenie operacji analizy. Jedynymi innymi flagami, z którymi można się połączyć NumberStyles.AllowHexSpecifier , są NumberStyles.AllowLeadingWhite i NumberStyles.AllowTrailingWhite. (Wyliczenie NumberStyles zawiera styl liczby złożonej, NumberStyles.HexNumber, który zawiera obie flagi odstępu).

Uwaga

s Jeśli parametr jest reprezentacją ciągu liczby szesnastkowej, nie może być poprzedzony żadną dekoracją (taką jak 0x lub &h), która odróżnia ją jako liczbę szesnastkową. To powoduje zgłoszenie wyjątku przez operację analizy.

Parametr provider jest implementacją IFormatProvider , której GetFormat metoda zwraca NumberFormatInfo obiekt, który dostarcza informacji specyficznych dla kultury o formacie s. Istnieją trzy sposoby użycia parametru provider w celu dostarczenia niestandardowych informacji o formatowaniu do operacji analizy:

  • Można przekazać rzeczywisty NumberFormatInfo obiekt, który dostarcza informacje o formatowaniu. (Jego implementacja GetFormat po prostu zwraca się).

  • Można przekazać obiekt określający kulturę CultureInfo , której formatowanie ma być używane. Jego NumberFormat właściwość zapewnia informacje o formatowaniu.

  • Możesz przekazać implementację niestandardową IFormatProvider . Jej GetFormat metoda musi utworzyć wystąpienie i zwrócić NumberFormatInfo obiekt, który dostarcza informacje o formatowaniu.

Jeśli provider parametr ma nullwartość , NumberFormatInfo używany jest obiekt bieżącej kultury.

Zobacz też

Dotyczy

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Źródło:
UInt16.cs
Źródło:
UInt16.cs
Źródło:
UInt16.cs

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Konwertuje reprezentację zakresu liczby w określonym stylu i formacie specyficznym dla kultury na odpowiednik 16-bitowej liczby całkowitej bez znaku.

public static ushort Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
[System.CLSCompliant(false)]
public static ushort Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
[System.CLSCompliant(false)]
public static ushort Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> uint16
[<System.CLSCompliant(false)>]
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> uint16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As UShort

Parametry

s
ReadOnlySpan<Char>

Zakres zawierający znaki reprezentujące liczbę do konwersji. Zakres jest interpretowany przy użyciu stylu określonego style przez parametr .

style
NumberStyles

Bitowa kombinacja wartości wyliczenia, które wskazują elementy stylu, które mogą być obecne w .s Typową wartością do określenia jest Integer.

provider
IFormatProvider

Obiekt, który dostarcza informacje o formatowaniu specyficznym dla kultury.s

Zwraca

16-bitowa liczba całkowita bez znaku równoważna liczbie określonej w elemencie s.

Implementuje

Atrybuty

Dotyczy

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Źródło:
UInt16.cs
Źródło:
UInt16.cs

Analizuje zakres znaków UTF-8 w wartości.

public static ushort Parse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> uint16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As UShort

Parametry

utf8Text
ReadOnlySpan<Byte>

Zakres znaków UTF-8 do analizy.

style
NumberStyles

Bitowa kombinacja stylów liczbowych, które mogą być obecne w .utf8Text

provider
IFormatProvider

Obiekt, który udostępnia informacje o formatowaniu specyficznym dla kultury.utf8Text

Zwraca

Wynik analizy utf8Text.

Implementuje

Dotyczy

Parse(String, IFormatProvider)

Źródło:
UInt16.cs
Źródło:
UInt16.cs
Źródło:
UInt16.cs

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Alternatywa zgodna ze specyfikacją CLS
System.Int32.Parse(String)

Konwertuje reprezentację ciągu liczby w określonym formacie specyficznym dla kultury na odpowiednik 16-bitowej liczby całkowitej bez znaku.

public:
 static System::UInt16 Parse(System::String ^ s, IFormatProvider ^ provider);
public:
 static System::UInt16 Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<System::UInt16>::Parse;
[System.CLSCompliant(false)]
public static ushort Parse (string s, IFormatProvider provider);
public static ushort Parse (string s, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static ushort Parse (string s, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * IFormatProvider -> uint16
static member Parse : string * IFormatProvider -> uint16
Public Shared Function Parse (s As String, provider As IFormatProvider) As UShort

Parametry

s
String

Ciąg reprezentujący liczbę, którą należy przekształcić.

provider
IFormatProvider

Obiekt, który dostarcza informacje o formatowaniu specyficznym dla kultury.s

Zwraca

16-bitowa liczba całkowita bez znaku równoważna liczbie określonej w elemencie s.

Implementuje

Atrybuty

Wyjątki

s nie ma poprawnego formatu.

s reprezentuje liczbę mniejszą niż UInt16.MinValue lub większą niż UInt16.MaxValue.

Przykłady

Poniższy przykład tworzy wystąpienie kultury niestandardowej, która używa dwóch znaków plus (++) jako znaku dodatniego. Następnie wywołuje metodę Parse(String, IFormatProvider) , aby przeanalizować tablicę ciągów przy użyciu CultureInfo obiektów reprezentujących zarówno tę kulturę niestandardową, jak i niezmienną kulturę.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      // Define a custom culture that uses "++" as a positive sign. 
      CultureInfo ci = new CultureInfo("");
      ci.NumberFormat.PositiveSign = "++";
      // Create an array of cultures.
      CultureInfo[] cultures = { ci, CultureInfo.InvariantCulture };
      // Create an array of strings to parse.
      string[] values = { "++1403", "-0", "+0", "+16034", 
                          Int16.MinValue.ToString(), "14.0", "18012" };
      // Parse the strings using each culture.
      foreach (CultureInfo culture in cultures)
      {
         Console.WriteLine("Parsing with the '{0}' culture.", culture.Name);
         foreach (string value in values)
         {
            try {
               ushort number = UInt16.Parse(value, culture);
               Console.WriteLine("   Converted '{0}' to {1}.", value, number);
            }
            catch (FormatException) {
               Console.WriteLine("   The format of '{0}' is invalid.", value);
            }
            catch (OverflowException) {
               Console.WriteLine("   '{0}' is outside the range of a UInt16 value.", value);
            }               
         }
      }
   }
}
// The example displays the following output:
//       Parsing with the  culture.
//          Converted '++1403' to 1403.
//          Converted '-0' to 0.
//          The format of '+0' is invalid.
//          The format of '+16034' is invalid.
//          '-32768' is outside the range of a UInt16 value.
//          The format of '14.0' is invalid.
//          Converted '18012' to 18012.
//       Parsing with the '' culture.
//          The format of '++1403' is invalid.
//          Converted '-0' to 0.
//          Converted '+0' to 0.
//          Converted '+16034' to 16034.
//          '-32768' is outside the range of a UInt16 value.
//          The format of '14.0' is invalid.
//          Converted '18012' to 18012.
open System
open System.Globalization

// Define a custom culture that uses "++" as a positive sign. 
let ci = CultureInfo ""
ci.NumberFormat.PositiveSign <- "++"
// Create an array of cultures.
let cultures = [| ci; CultureInfo.InvariantCulture |]
// Create an array of strings to parse.
let values = 
    [| "++1403"; "-0"; "+0"; "+16034" 
       string Int16.MinValue; "14.0"; "18012" |]
// Parse the strings using each culture.
for culture in cultures do
    printfn $"Parsing with the '{culture.Name}' culture."
    for value in values do
        try
            let number = UInt16.Parse(value, culture)
            printfn $"   Converted '{value}' to {number}."
        with
        | :? FormatException ->
            printfn $"   The format of '{value}' is invalid."
        | :? OverflowException ->
            printfn $"   '{value}' is outside the range of a UInt16 value."
// The example displays the following output:
//       Parsing with the  culture.
//          Converted '++1403' to 1403.
//          Converted '-0' to 0.
//          The format of '+0' is invalid.
//          The format of '+16034' is invalid.
//          '-32768' is outside the range of a UInt16 value.
//          The format of '14.0' is invalid.
//          Converted '18012' to 18012.
//       Parsing with the '' culture.
//          The format of '++1403' is invalid.
//          Converted '-0' to 0.
//          Converted '+0' to 0.
//          Converted '+16034' to 16034.
//          '-32768' is outside the range of a UInt16 value.
//          The format of '14.0' is invalid.
//          Converted '18012' to 18012.
Imports System.Globalization

Module Example
   Public Sub Main()
      ' Define a custom culture that uses "++" as a positive sign. 
      Dim ci As CultureInfo = New CultureInfo("")
      ci.NumberFormat.PositiveSign = "++"
      ' Create an array of cultures.
      Dim cultures() As CultureInfo = { ci, CultureInfo.InvariantCulture }
      ' Create an array of strings to parse.
      Dim values() As String = { "++1403", "-0", "+0", "+16034", _
                                 Int16.MinValue.ToString(), "14.0", "18012" }
      ' Parse the strings using each culture.
      For Each culture As CultureInfo In cultures
         Console.WriteLine("Parsing with the '{0}' culture.", culture.Name)
         For Each value As String In values
            Try
               Dim number As UShort = UInt16.Parse(value, culture)
               Console.WriteLine("   Converted '{0}' to {1}.", value, number)
            Catch e As FormatException
               Console.WriteLine("   The format of '{0}' is invalid.", value)
            Catch e As OverflowException
               Console.WriteLine("   '{0}' is outside the range of a UInt16 value.", value)
            End Try               
         Next
      Next
   End Sub
End Module
' The example displays the following output:
'       Parsing with the  culture.
'          Converted '++1403' to 1403.
'          Converted '-0' to 0.
'          The format of '+0' is invalid.
'          The format of '+16034' is invalid.
'          '-32768' is outside the range of a UInt16 value.
'          The format of '14.0' is invalid.
'          Converted '18012' to 18012.
'       Parsing with the '' culture.
'          The format of '++1403' is invalid.
'          Converted '-0' to 0.
'          Converted '+0' to 0.
'          Converted '+16034' to 16034.
'          '-32768' is outside the range of a UInt16 value.
'          The format of '14.0' is invalid.
'          Converted '18012' to 18012.

Uwagi

Parametr s zawiera liczbę formularzy:

[ws] [podpis] digits[ws]

Elementy w nawiasach kwadratowych ([ i ]) są opcjonalne. W tabeli poniżej opisano każdy element.

Element Opis
ws Opcjonalny odstęp.
znak Opcjonalny znak lub znak ujemny, jeśli s reprezentuje wartość zero.
cyfry Sekwencja cyfr od 0 do 9.

Parametr s jest interpretowany przy użyciu NumberStyles.Integer stylu. Oprócz cyfr dziesiętnych wartości bajtowej dozwolone są tylko spacje wiodące i końcowe wraz z znakiem wiodącym. (Jeśli znak ujemny jest obecny, s musi reprezentować wartość zero lub metoda zgłasza OverflowExceptionwartość .) Aby jawnie zdefiniować elementy stylu wraz z informacjami o formatowaniu specyficznymi dla kultury, które mogą być obecne w sprogramie , użyj Parse(String, NumberStyles, IFormatProvider) metody .

Parametr provider jest implementacją IFormatProvider , której GetFormat metoda zwraca NumberFormatInfo obiekt, który dostarcza informacji specyficznych dla kultury o formacie s. Istnieją trzy sposoby użycia parametru provider w celu dostarczenia niestandardowych informacji o formatowaniu do operacji analizy:

  • Można przekazać rzeczywisty NumberFormatInfo obiekt, który dostarcza informacje o formatowaniu. (Jego implementacja GetFormat po prostu zwraca się).

  • Można przekazać obiekt określający kulturę CultureInfo , której formatowanie ma być używane. Jego NumberFormat właściwość zapewnia informacje o formatowaniu.

  • Możesz przekazać implementację niestandardową IFormatProvider . Jej GetFormat metoda musi utworzyć wystąpienie i zwrócić NumberFormatInfo obiekt, który dostarcza informacje o formatowaniu.

Jeśli provider wartość to null, NumberFormatInfo używana jest wartość dla bieżącej kultury.

Zobacz też

Dotyczy

Parse(String, NumberStyles)

Źródło:
UInt16.cs
Źródło:
UInt16.cs
Źródło:
UInt16.cs

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Konwertuje reprezentację ciągu liczby w określonym stylu na odpowiednik 16-bitowej liczby całkowitej bez znaku.

Ta metoda nie jest zgodna ze specyfikacją CLS. Alternatywą zgodną ze standardem CLS jest Parse(String, NumberStyles).

public:
 static System::UInt16 Parse(System::String ^ s, System::Globalization::NumberStyles style);
[System.CLSCompliant(false)]
public static ushort Parse (string s, System.Globalization.NumberStyles style);
public static ushort Parse (string s, System.Globalization.NumberStyles style);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles -> uint16
static member Parse : string * System.Globalization.NumberStyles -> uint16
Public Shared Function Parse (s As String, style As NumberStyles) As UShort

Parametry

s
String

Ciąg reprezentujący liczbę, którą należy przekształcić. Ciąg jest interpretowany przy użyciu stylu określonego style przez parametr .

style
NumberStyles

Bitowa kombinacja wartości wyliczenia, które określają dozwolony format .s Typową wartością do określenia jest Integer.

Zwraca

16-bitowa liczba całkowita bez znaku równoważna liczbie określonej w elemencie s.

Atrybuty

Wyjątki

style nie jest wartością NumberStyles .

-lub-

style nie jest kombinacją AllowHexSpecifier wartości i HexNumber .

s nie jest w formacie zgodnym z parametrem style.

s reprezentuje liczbę mniejszą niż UInt16.MinValue lub większą niż UInt16.MaxValue.

-lub-

s zawiera cyfry niezerowe, ułamkowe.

Przykłady

Poniższy przykład próbuje przeanalizować każdy element w tablicy ciągów NumberStyles przy użyciu liczby wartości.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] values = { " 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.0e-2" };
      NumberStyles whitespace =  NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite;
      NumberStyles[] styles = { NumberStyles.None, whitespace, 
                                NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, 
                                NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, 
                                NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint };

      // Attempt to convert each number using each style combination.
      foreach (string value in values)
      {
         Console.WriteLine("Attempting to convert '{0}':", value);
         foreach (NumberStyles style in styles)
         {
            try {
               ushort number = UInt16.Parse(value, style);
               Console.WriteLine("   {0}: {1}", style, number);
            }   
            catch (FormatException) {
               Console.WriteLine("   {0}: Bad Format", style);
            }
         }
         Console.WriteLine();
      }
   }
}
// The example display the following output:
//    Attempting to convert ' 214 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: 214
//       Integer, AllowTrailingSign: 214
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '1,064':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: 1064
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '(0)':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '1241+':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 1241
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' + 214 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' +214 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 214
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '2153.0':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 2153
//    
//    Attempting to convert '1e03':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 1000
//    
//    Attempting to convert '1300.0e-2':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 13
open System
open System.Globalization

let values = [| " 214 "; "1,064"; "(0)"; "1241+"; " + 214 "; " +214 "; "2153.0"; "1e03"; "1300.0e-2" |]
let whitespace =  NumberStyles.AllowLeadingWhite ||| NumberStyles.AllowTrailingWhite
let styles = 
    [| NumberStyles.None; whitespace 
       NumberStyles.AllowLeadingSign ||| NumberStyles.AllowTrailingSign ||| whitespace 
       NumberStyles.AllowThousands ||| NumberStyles.AllowCurrencySymbol
       NumberStyles.AllowExponent ||| NumberStyles.AllowDecimalPoint |]

// Attempt to convert each number using each style combination.
for value in values do
    printfn $"Attempting to convert '{value}':"
    for style in styles do
        try
            let number = UInt16.Parse(value, style)
            printfn $"   {style}: {number}"
        with :? FormatException ->
            printfn $"   {style}: Bad Format"
    printfn ""
// The example display the following output:
//    Attempting to convert ' 214 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: 214
//       Integer, AllowTrailingSign: 214
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '1,064':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: 1064
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '(0)':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '1241+':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 1241
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' + 214 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' +214 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 214
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '2153.0':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 2153
//    
//    Attempting to convert '1e03':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 1000
//    
//    Attempting to convert '1300.0e-2':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 13
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim values() As String = { " 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.0e-2" }
      Dim whitespace As NumberStyles =  NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite
      Dim styles() As NumberStyles = { NumberStyles.None, _
                                       whitespace, _
                                       NumberStyles.AllowLeadingSign Or NumberStyles.AllowTrailingSign Or whitespace, _
                                       NumberStyles.AllowThousands Or NumberStyles.AllowCurrencySymbol, _
                                       NumberStyles.AllowExponent Or NumberStyles.AllowDecimalPoint }

      ' Attempt to convert each number using each style combination.
      For Each value As String In values
         Console.WriteLine("Attempting to convert '{0}':", value)
         For Each style As NumberStyles In styles
            Try
               Dim number As UShort = UInt16.Parse(value, style)
               Console.WriteLine("   {0}: {1}", style, number)
            Catch e As FormatException
               Console.WriteLine("   {0}: Bad Format", style)
            End Try         
         Next
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output:
'    Attempting to convert ' 214 ':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: 214
'       Integer, AllowTrailingSign: 214
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '1,064':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: 1064
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '(0)':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '1241+':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: 1241
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert ' + 214 ':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert ' +214 ':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: 214
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '2153.0':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: 2153
'    
'    Attempting to convert '1e03':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: 1000
'    
'    Attempting to convert '1300.0e-2':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: 13

Uwagi

Parametr style definiuje elementy stylu (takie jak biały znak, symbol znaku dodatniego lub ujemnego, symbol separatora grupy lub symbol separatora dziesiętnego), które są dozwolone w parametrze s dla operacji analizy pomyślne. style musi być kombinacją flag bitowych z NumberStyles wyliczenia. Parametr style sprawia, że ta metoda jest przydatna, gdy s zawiera reprezentację ciągu wartości szesnastkowej, gdy system liczbowy (dziesiętny lub szesnastkowy) reprezentowany przez s element jest znany tylko w czasie wykonywania lub gdy chcesz uniemożliwić biały znak lub symbol znaku w .s

W zależności od wartości styleparametr może s zawierać następujące elementy:

[ws] [$][znak][cyfry,]cyfry[.fractional_digits][E[znak]exponential_digits][ws]

Elementy w nawiasach kwadratowych ([ i ]) są opcjonalne. Jeśli style parametr zawiera NumberStyles.AllowHexSpecifierparametr , s może zawierać następujące elementy:

[ws] hexdigits[ws]

W tabeli poniżej opisano każdy element.

Element Opis
Ws Opcjonalny odstęp. Białe znaki mogą pojawić się na początku s , jeśli style zawiera flagę NumberStyles.AllowLeadingWhite , i może pojawić się na końcu s , jeśli style zawiera flagę NumberStyles.AllowTrailingWhite .
$ Symbol waluty specyficzny dla kultury. Jego pozycja w ciągu jest definiowana przez NumberFormatInfo.CurrencyNegativePattern właściwości i NumberFormatInfo.CurrencyPositivePattern bieżącej kultury. Symbol waluty bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowCurrencySymbol .
sign Opcjonalny znak. Znak może pojawić się na początku s , jeśli style zawiera flagę NumberStyles.AllowLeadingSign i może pojawić się na końcu s , jeśli style zawiera flagę NumberStyles.AllowTrailingSign . Nawiasy mogą służyć s do wskazywania wartości ujemnej, jeśli style zawiera flagę NumberStyles.AllowParentheses . Jednak symbol znaku ujemnego może być używany tylko z zerem; w przeciwnym razie metoda zgłasza błąd OverflowException.
Cyfr

fractional_digits

exponential_digits
Sekwencja cyfr od 0 do 9. W przypadku fractional_digits tylko cyfra 0 jest prawidłowa.
, Symbol separatora grupy specyficzny dla kultury. Separator grup bieżącej kultury może pojawić się w pliku , s jeśli style zawiera flagę NumberStyles.AllowThousands .
. Symbol dziesiętny specyficzny dla kultury. Symbol punktu dziesiętnego bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowDecimalPoint . Tylko cyfra 0 może być wyświetlana jako cyfra ułamkowa dla operacji analizy, która zakończy się powodzeniem; jeśli fractional_digits zawiera inną cyfrę FormatException , zostanie zgłoszony.
E Znak „e” lub „E”, który wskazuje, że wartość jest reprezentowana w zapisie wykładniczym (naukowym). Parametr s może reprezentować liczbę w notacji wykładniczej, jeśli style zawiera flagę NumberStyles.AllowExponent .
hexdigits Sekwencja cyfr szesnastkowych od 0 do f lub od 0 do F.

Uwaga

Wszelkie znaki zakończenia NUL (U+0000) w obiekcie s są ignorowane przez operację analizowania, niezależnie od wartości argumentu style .

Ciąg z cyframi (odpowiadający NumberStyles.None stylowi) zawsze analizuje się pomyślnie, jeśli znajduje się on w zakresie UInt16 typu. Większość pozostałych NumberStyles elementów członkowskich kontroluje, które mogą być obecne, ale nie są wymagane do obecności w ciągu wejściowym. Poniższa tabela wskazuje, jak poszczególne NumberStyles elementy członkowskie wpływają na elementy, które mogą być obecne w elemecie s.

NumberStyles Wartość Elementy dozwolone s oprócz cyfr
None Tylko element cyfry .
AllowDecimalPoint Elementy punktów dziesiętnych (.) i cyfr ułamkowych .
AllowExponent Znak "e" lub "E", który wskazuje notację wykładniczą wraz z exponential_digits.
AllowLeadingWhite Element ws na początku s.
AllowTrailingWhite Element ws na końcu selementu .
AllowLeadingSign Element znaku na początku s.
AllowTrailingSign Element znaku na końcu elementu s.
AllowParentheses Element znaku w postaci nawiasów otaczających wartość liczbową.
AllowThousands Element separatora grupy (,).
AllowCurrencySymbol Element określający walutę ($).
Currency Wszystkie elementy. s Nie można jednak reprezentować liczby szesnastkowej ani liczby w notacji wykładniczej.
Float Element ws na początku lub na końcu s, znak na początku s, i symbol dziesiętny (.). Parametr s może również używać notacji wykładniczej.
Number wsElementy separatora grup (sign,) i separatora dziesiętnego (.).
Any Wszystkie elementy. s Nie można jednak reprezentować liczby szesnastkowej.

W przeciwieństwie do innych NumberStyles wartości, które umożliwiają, ale nie wymagają, obecność określonych elementów stylu w elemecie , NumberStyles.AllowHexSpecifier wartość stylu oznacza, że poszczególne znaki liczbowe w s obiekcie ssą zawsze interpretowane jako znaki szesnastkowe. Prawidłowe znaki szesnastkowe to 0-9, A-F i a-f. Prefiks, taki jak "0x", nie jest obsługiwany i powoduje niepowodzenie operacji analizowania. Jedyną inną flagą, którą można połączyć z parametrem style , są NumberStyles.AllowLeadingWhite i NumberStyles.AllowTrailingWhite. (Wyliczenie NumberStyles zawiera styl liczb złożonych, NumberStyles.HexNumber, który zawiera obie flagi odstępu).

Uwaga

Jeśli s jest reprezentacją ciągu liczby szesnastkowej, nie może być poprzedzona żadną dekoracją (taką jak 0x lub &h), która rozróżnia ją jako liczbę szesnastkowa. To powoduje niepowodzenie konwersji.

Parametr s jest analizowany przy użyciu informacji o formatowaniu w obiekcie zainicjowanym NumberFormatInfo dla bieżącej kultury systemu. Aby określić kulturę, której informacje dotyczące formatowania są używane do operacji analizowania, wywołaj Parse(String, NumberStyles, IFormatProvider) przeciążenie.

Zobacz też

Dotyczy

Parse(ReadOnlySpan<Char>, IFormatProvider)

Źródło:
UInt16.cs
Źródło:
UInt16.cs
Źródło:
UInt16.cs

Analizuje zakres znaków w wartości.

public:
 static System::UInt16 Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<System::UInt16>::Parse;
public static ushort Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> uint16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As UShort

Parametry

s
ReadOnlySpan<Char>

Zakres znaków do przeanalizowania.

provider
IFormatProvider

Obiekt, który udostępnia informacje o formatowaniu specyficznym dla kultury dotyczące selementu .

Zwraca

Wynik analizy s.

Implementuje

Dotyczy

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Źródło:
UInt16.cs
Źródło:
UInt16.cs

Analizuje zakres znaków UTF-8 w wartość.

public:
 static System::UInt16 Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<System::UInt16>::Parse;
public static ushort Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> uint16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As UShort

Parametry

utf8Text
ReadOnlySpan<Byte>

Zakres znaków UTF-8 do przeanalizowania.

provider
IFormatProvider

Obiekt, który udostępnia informacje o formatowaniu specyficznym dla kultury dotyczące utf8Textelementu .

Zwraca

Wynik analizy utf8Text.

Implementuje

Dotyczy

Parse(String)

Źródło:
UInt16.cs
Źródło:
UInt16.cs
Źródło:
UInt16.cs

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Alternatywa zgodna ze specyfikacją CLS
System.Int32.Parse(String)

Konwertuje ciąg reprezentujący liczbę na odpowiadającą mu 16-bitową liczbę całkowitą bez znaku.

public:
 static System::UInt16 Parse(System::String ^ s);
[System.CLSCompliant(false)]
public static ushort Parse (string s);
public static ushort Parse (string s);
[<System.CLSCompliant(false)>]
static member Parse : string -> uint16
static member Parse : string -> uint16
Public Shared Function Parse (s As String) As UShort

Parametry

s
String

Ciąg reprezentujący liczbę, którą należy przekształcić.

Zwraca

16-bitowa liczba całkowita bez znaku równoważna liczbie zawartej w elemencie s.

Atrybuty

Wyjątki

s nie jest w poprawnym formacie.

s reprezentuje liczbę mniejszą niż UInt16.MinValue lub większą niż UInt16.MaxValue.

Przykłady

Poniższy przykład wywołuje metodę Parse(String) , aby przekonwertować każdy element w tablicy ciągów na niepodpisaną liczbę całkowitą 16-bitową.

using System;

public class Example
{
   public static void Main()
   {
      string[] values = { "-0", "17", "-12", "185", "66012", "+0", 
                          "", null, "16.1", "28.0", "1,034" };
      foreach (string value in values)
      {
         try {
            ushort number = UInt16.Parse(value);
            Console.WriteLine("'{0}' --> {1}", value, number);
         }
         catch (FormatException) {
            Console.WriteLine("'{0}' --> Bad Format", value);
         }
         catch (OverflowException) {   
            Console.WriteLine("'{0}' --> OverflowException", value);
         }
         catch (ArgumentNullException) {
            Console.WriteLine("'{0}' --> Null", value);
         }
      }                                 
   }
}
// The example displays the following output:
//       '-0' --> 0
//       '17' --> 17
//       '-12' --> OverflowException
//       '185' --> 185
//       '66012' --> OverflowException
//       '+0' --> 0
//       '' --> Bad Format
//       '' --> Null
//       '16.1' --> Bad Format
//       '28.0' --> Bad Format
//       '1,034' --> Bad Format
open System

let values = 
    [| "-0"; "17"; "-12"; "185"; "66012"; "+0" 
       ""; null; "16.1"; "28.0"; "1,034" |]
for value in values do
    try
        let number = UInt16.Parse value
        printfn $"'{value}' --> {number}"
    with
    | :? FormatException ->
        printfn $"'{value}' --> Bad Format"
    | :? OverflowException ->
        printfn $"'{value}' --> OverflowException"
    | :? ArgumentNullException ->
        printfn $"'{value}' --> Null"
// The example displays the following output:
//       '-0' --> 0
//       '17' --> 17
//       '-12' --> OverflowException
//       '185' --> 185
//       '66012' --> OverflowException
//       '+0' --> 0
//       '' --> Bad Format
//       '' --> Null
//       '16.1' --> Bad Format
//       '28.0' --> Bad Format
//       '1,034' --> Bad Format
Module Example
   Public Sub Main()
      Dim values() As String = { "-0", "17", "-12", "185", "66012", _ 
                                 "+0", "", Nothing, "16.1", "28.0", _
                                 "1,034" }
      For Each value As String In values
         Try
            Dim number As UShort = UInt16.Parse(value)
            Console.WriteLine("'{0}' --> {1}", value, number)
         Catch e As FormatException
            Console.WriteLine("'{0}' --> Bad Format", value)
         Catch e As OverflowException   
            Console.WriteLine("'{0}' --> OverflowException", value)
         Catch e As ArgumentNullException
            Console.WriteLine("'{0}' --> Null", value)
         End Try
      Next                                 
   End Sub
End Module
' The example displays the following output:
'       '-0' --> 0
'       '17' --> 17
'       '-12' --> OverflowException
'       '185' --> 185
'       '66012' --> OverflowException
'       '+0' --> 0
'       '' --> Bad Format
'       '' --> Null
'       '16.1' --> Bad Format
'       '28.0' --> Bad Format
'       '1,034' --> Bad Format

Uwagi

Parametr s powinien być reprezentacją ciągu liczby w poniższym formularzu.

[ws] [znak] cyfry[ws]

Elementy w nawiasach kwadratowych ([ i ]) są opcjonalne. W tabeli poniżej opisano każdy element.

Element Opis
Ws Opcjonalny odstęp.
sign Opcjonalny znak. Prawidłowe znaki są określane przez NumberFormatInfo.NegativeSign właściwości i NumberFormatInfo.PositiveSign bieżącej kultury. Jednak symbol znaku ujemnego może być używany tylko z zerem; w przeciwnym razie metoda zgłasza błąd OverflowException.
Cyfr Sekwencja cyfr od 0 do 9. Wszystkie zera wiodące są ignorowane.

Uwaga

Ciąg określony przez s parametr jest interpretowany przy użyciu NumberStyles.Integer stylu. Nie może zawierać żadnych separatorów grup ani separatorów dziesiętnych, a także mieć części dziesiętnej.

Parametr s jest analizowany przy użyciu informacji o formatowaniu w obiekcie zainicjowanym System.Globalization.NumberFormatInfo dla bieżącej kultury systemu. Aby uzyskać więcej informacji, zobacz NumberFormatInfo.CurrentInfo. Aby przeanalizować ciąg przy użyciu informacji o formatowaniu określonej kultury, użyj Parse(String, IFormatProvider) metody .

Zobacz też

Dotyczy