UInt16.Parse Metod

Definition

Konverterar strängrepresentationen av ett tal till dess 16-bitars osignerade heltalsekvivalent.

Överlagringar

Name Description
Parse(String, NumberStyles, IFormatProvider)

Konverterar strängrepresentationen av ett tal i ett angivet format och kulturspecifikt format till dess 16-bitars osignerade heltalsekvivalent.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Konverterar spanrepresentationen av ett tal i ett angivet format och kulturspecifikt format till dess 16-bitars osignerade heltalsmotsvarighet.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Parsar ett intervall med UTF-8 tecken till ett värde.

Parse(String, IFormatProvider)

Konverterar strängrepresentationen av ett tal i ett angivet kulturspecifikt format till dess 16-bitars osignerade heltalsekvivalent.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Parsar ett teckenintervall till ett värde.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Parsar ett intervall med UTF-8 tecken till ett värde.

Parse(String)

Konverterar strängrepresentationen av ett tal till dess 16-bitars osignerade heltalsekvivalent.

Parse(String, NumberStyles)

Konverterar strängrepresentationen av ett tal i ett angivet format till dess 16-bitars osignerade heltalsekvivalent.

Den här metoden är inte CLS-kompatibel. Det CLS-kompatibla alternativet är Parse(String, NumberStyles).

Parse(String, NumberStyles, IFormatProvider)

Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs

Viktigt!

Detta API uppfyller inte CLS.

Alternativ som uppfyller CLS
System.Int32.Parse(String)

Konverterar strängrepresentationen av ett tal i ett angivet format och kulturspecifikt format till dess 16-bitars osignerade heltalsekvivalent.

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

Parametrar

s
String

En sträng som representerar talet som ska konverteras. Strängen tolkas med hjälp av det format som anges av parametern style .

style
NumberStyles

En bitvis kombination av uppräkningsvärden som anger de formatelement som kan finnas i s. Ett typiskt värde att ange är Integer.

provider
IFormatProvider

Ett objekt som tillhandahåller kulturspecifik formateringsinformation om s.

Returer

Ett 16-bitars osignerat heltal som motsvarar det tal som anges i s.

Implementeringar

Attribut

Undantag

s är null.

style är inte ett NumberStyles värde.

-eller-

style är inte en kombination av AllowHexSpecifier och HexNumber värden.

s är inte i ett format som är kompatibelt med style.

s representerar ett tal som är mindre än UInt16.MinValue eller större än UInt16.MaxValue.

-eller-

s innehåller icke-noll, bråktalssiffror.

Exempel

I följande exempel används Parse(String, NumberStyles, IFormatProvider) metoden för att konvertera olika strängrepresentationer av tal till 16-bitars osignerade heltalsvärden.

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.

Kommentarer

Parametern style definierar formatelementen (till exempel blanksteg eller symbolen för positiva eller negativa tecken) som tillåts i parametern s för att parsningsåtgärden ska lyckas. Det måste vara en kombination av bitflaggor från NumberStyles uppräkningen.

Beroende på värdet för stylekan parametern s innehålla följande element:

[ws][$][sign]digits[.fractional_digits][E[sign]exponential_digits][ws]

Element inom hakparenteser ([ och ]) är valfria. Om style innehåller NumberStyles.AllowHexSpecifierkan parametern s innehålla följande element:

[ws]hexdigits[ws]

I följande tabell beskrivs varje element.

Element Description
Ws Valfritt blanksteg. Tomt utrymme kan visas i början av s om style innehåller NumberStyles.AllowLeadingWhite flaggan, och det kan visas i slutet av s om style innehåller NumberStyles.AllowTrailingWhite flaggan.
$ En kulturspecifik valutasymbol. Dess position i strängen definieras av CurrencyPositivePattern egenskapen för objektet NumberFormatInfo som returneras av GetFormat parameterns provider metod. Valutasymbolen kan visas i s om style den NumberStyles.AllowCurrencySymbol innehåller flaggan.
signera Ett valfritt tecken. (Metoden genererar ett OverflowException om s innehåller ett negativt tecken och representerar ett tal som inte är noll.) Tecknet kan visas i början av s om style innehåller NumberStyles.AllowLeadingSign flaggan, och det kan visas i slutet av s om style innehåller NumberStyles.AllowTrailingSign flaggan. Parenteser kan användas i s för att ange ett negativt värde om style den NumberStyles.AllowParentheses innehåller flaggan.
Siffror En sekvens med siffror från 0 till 9.
. Ett kulturspecifikt decimaltecken. Den aktuella kulturens decimaltecken kan visas i s om style den NumberStyles.AllowDecimalPoint innehåller flaggan.
fractional_digits En eller flera förekomster av siffran 0–9 om style den NumberStyles.AllowExponent innehåller flaggan, eller en eller flera förekomster av siffran 0 om den inte gör det. Bråksiffror kan bara visas i s om style den NumberStyles.AllowDecimalPoint innehåller flaggan.
E Tecknet "e" eller "E", som anger att värdet representeras i exponentiell (vetenskaplig) notation. Parametern s kan representera ett tal i exponentiell notation om style den NumberStyles.AllowExponent innehåller flaggan.
exponential_digits En sekvens med siffror från 0 till 9. Parametern s kan representera ett tal i exponentiell notation om style den NumberStyles.AllowExponent innehåller flaggan.
hexdigits En sekvens med hexadecimala siffror från 0 till f eller 0 till och med F.

Note

Alla avslutande NUL-tecken (U+0000) i s ignoreras av parsningsåtgärden, oavsett argumentets style värde.

En sträng med endast decimalsiffror (vilket motsvarar NumberStyles.None formatet) parsar alltid korrekt. De flesta av de återstående NumberStyles medlemmarna styr element som kan finnas, men som inte måste finnas i den här indatasträngen. Följande tabell visar hur enskilda NumberStyles medlemmar påverkar de element som kan finnas i s.

Icke-sammansatta NumberStyles värden Element som tillåts s utöver siffror
NumberStyles.None Endast decimalsiffror.
NumberStyles.AllowDecimalPoint Decimaltecknet (.) och fractional_digits element. Men om formatmallen NumberStyles.AllowExponent inte innehåller flaggan måste fractional_digits endast bestå av en eller flera 0 siffror. Annars genereras en OverflowException .
NumberStyles.AllowExponent Tecknet "e" eller "E", som anger exponentiell notation, tillsammans med exponential_digits.
NumberStyles.AllowLeadingWhite WS-elementet i början av s.
NumberStyles.AllowTrailingWhite WS-elementet i slutet av s.
NumberStyles.AllowLeadingSign Ett tecken före siffror.
NumberStyles.AllowTrailingSign Ett tecken efter siffror.
NumberStyles.AllowParentheses Parenteser före och efter siffror för att indikera ett negativt värde.
NumberStyles.AllowThousands Gruppavgränsaren (,).
NumberStyles.AllowCurrencySymbol Valutaelementet ($).

NumberStyles.AllowHexSpecifier Om flaggan används s måste vara ett hexadecimalt värde. Giltiga hexadecimala siffror är 0 till 9, a till och med f och A till och med F. Ett prefix, till exempel "0x", stöds inte och gör att parsningsåtgärden misslyckas. De enda andra flaggorna som kan kombineras med NumberStyles.AllowHexSpecifier är NumberStyles.AllowLeadingWhite och NumberStyles.AllowTrailingWhite. (Uppräkningen NumberStyles innehåller ett sammansatt talformat, NumberStyles.HexNumber, som innehåller båda blankstegsflaggor.)

Note

Om parametern s är strängrepresentationen av ett hexadecimalt tal kan den inte föregås av någon dekoration (till exempel 0x eller &h) som särskiljer den som ett hexadecimalt tal. Detta gör att parsningsåtgärden utlöser ett undantag.

Parametern provider är en IFormatProvider implementering vars GetFormat metod returnerar ett NumberFormatInfo objekt som tillhandahåller kulturspecifik information om formatet för s. Det finns tre sätt att använda parametern provider för att ange anpassad formateringsinformation till parsningsåtgärden:

  • Du kan skicka det faktiska NumberFormatInfo objektet som innehåller formateringsinformation. (Dess implementering av GetFormat returnerar helt enkelt sig själv.)

  • Du kan skicka ett CultureInfo objekt som anger den kultur vars formatering ska användas. Dess NumberFormat egenskap innehåller formateringsinformation.

  • Du kan genomföra en anpassad IFormatProvider implementering. Dess GetFormat metod måste instansiera och returnera det NumberFormatInfo objekt som tillhandahåller formateringsinformation.

Om provider är nullNumberFormatInfo används objektet för den aktuella kulturen.

Se även

Gäller för

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs

Viktigt!

Detta API uppfyller inte CLS.

Konverterar spanrepresentationen av ett tal i ett angivet format och kulturspecifikt format till dess 16-bitars osignerade heltalsmotsvarighet.

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

Parametrar

s
ReadOnlySpan<Char>

Ett intervall som innehåller de tecken som representerar talet som ska konverteras. Intervallet tolkas med hjälp av det format som anges av parametern style .

style
NumberStyles

En bitvis kombination av uppräkningsvärden som anger de formatelement som kan finnas i s. Ett typiskt värde att ange är Integer.

provider
IFormatProvider

Ett objekt som tillhandahåller kulturspecifik formateringsinformation om s.

Returer

Ett 16-bitars osignerat heltal som motsvarar det tal som anges i s.

Implementeringar

Attribut

Gäller för

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs

Parsar ett intervall med UTF-8 tecken till ett värde.

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

Parametrar

utf8Text
ReadOnlySpan<Byte>

Intervallet för UTF-8 tecken att parsa.

style
NumberStyles

En bitvis kombination av talformat som kan finnas i utf8Text.

provider
IFormatProvider

Ett objekt som tillhandahåller kulturspecifik formateringsinformation om utf8Text.

Returer

Resultatet av parsning utf8Text.

Implementeringar

Gäller för

Parse(String, IFormatProvider)

Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs

Viktigt!

Detta API uppfyller inte CLS.

Alternativ som uppfyller CLS
System.Int32.Parse(String)

Konverterar strängrepresentationen av ett tal i ett angivet kulturspecifikt format till dess 16-bitars osignerade heltalsekvivalent.

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

Parametrar

s
String

En sträng som representerar talet som ska konverteras.

provider
IFormatProvider

Ett objekt som tillhandahåller kulturspecifik formateringsinformation om s.

Returer

Ett 16-bitars osignerat heltal som motsvarar det tal som anges i s.

Implementeringar

Attribut

Undantag

s är null.

s är inte i rätt format.

s representerar ett tal som är mindre än UInt16.MinValue eller större än UInt16.MaxValue.

Exempel

I följande exempel instansieras en anpassad kultur som använder två plustecken (++) som ett positivt tecken. Sedan anropas Parse(String, IFormatProvider) metoden för att parsa en matris med strängar med hjälp CultureInfo av objekt som representerar både den här anpassade kulturen och den invarianta kulturen.

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.

Kommentarer

Parametern s innehåller ett antal av formuläret:

[ws][sign]digits[ws]

Objekt inom hakparenteser ([ och ]) är valfria. I följande tabell beskrivs varje element.

Element Description
Ws Valfritt blanksteg.
sign Ett valfritt tecken eller ett negativt tecken om s representerar värdet noll.
Siffror En sekvens med siffror mellan 0 och 9.

Parametern s tolkas med formatet NumberStyles.Integer . Förutom bytevärdets decimalsiffror tillåts endast inledande och avslutande blanksteg tillsammans med ett inledande tecken. (Om det negativa tecknet finns s måste det representera ett värde på noll eller så genererar metoden . OverflowException) Om du vill definiera formatelementen explicit tillsammans med den kulturspecifika formateringsinformation som kan finnas i sanvänder du Parse(String, NumberStyles, IFormatProvider) metoden .

Parametern provider är en IFormatProvider implementering vars GetFormat metod returnerar ett NumberFormatInfo objekt som tillhandahåller kulturspecifik information om formatet för s. Det finns tre sätt att använda parametern provider för att ange anpassad formateringsinformation till parsningsåtgärden:

  • Du kan skicka det faktiska NumberFormatInfo objektet som innehåller formateringsinformation. (Dess implementering av GetFormat returnerar helt enkelt sig själv.)

  • Du kan skicka ett CultureInfo objekt som anger den kultur vars formatering ska användas. Dess NumberFormat egenskap innehåller formateringsinformation.

  • Du kan genomföra en anpassad IFormatProvider implementering. Dess GetFormat metod måste instansiera och returnera det NumberFormatInfo objekt som tillhandahåller formateringsinformation.

Om provider är nullNumberFormatInfo används för den aktuella kulturen.

Se även

Gäller för

Parse(ReadOnlySpan<Char>, IFormatProvider)

Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs

Parsar ett teckenintervall till ett värde.

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

Parametrar

s
ReadOnlySpan<Char>

Det intervall med tecken som ska parsas.

provider
IFormatProvider

Ett objekt som tillhandahåller kulturspecifik formateringsinformation om s.

Returer

Resultatet av parsning s.

Implementeringar

Gäller för

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs

Parsar ett intervall med UTF-8 tecken till ett värde.

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

Parametrar

utf8Text
ReadOnlySpan<Byte>

Intervallet för UTF-8 tecken att parsa.

provider
IFormatProvider

Ett objekt som tillhandahåller kulturspecifik formateringsinformation om utf8Text.

Returer

Resultatet av parsning utf8Text.

Implementeringar

Gäller för

Parse(String)

Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs

Viktigt!

Detta API uppfyller inte CLS.

Alternativ som uppfyller CLS
System.Int32.Parse(String)

Konverterar strängrepresentationen av ett tal till dess 16-bitars osignerade heltalsekvivalent.

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

Parametrar

s
String

En sträng som representerar talet som ska konverteras.

Returer

Ett 16-bitars osignerat heltal som motsvarar talet i s.

Attribut

Undantag

s är null.

s är inte i rätt format.

s representerar ett tal som är mindre än UInt16.MinValue eller större än UInt16.MaxValue.

Exempel

I följande exempel anropas Parse(String) metoden för att konvertera varje element i en strängmatris till ett osignerat 16-bitars heltal.

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

Kommentarer

Parametern s ska vara strängrepresentationen av ett tal i följande formulär.

[ws][sign]digits[ws]

Element inom hakparenteser ([ och ]) är valfria. I följande tabell beskrivs varje element.

Element Description
Ws Valfritt blanksteg.
signera Ett valfritt tecken. Giltiga teckentecken bestäms av NumberFormatInfo.NegativeSign egenskaperna och NumberFormatInfo.PositiveSign för den aktuella kulturen. Den negativa teckensymbolen kan dock endast användas med noll. annars genererar metoden en OverflowException.
Siffror En sekvens med siffror mellan 0 och 9. Inledande nollor ignoreras.

Note

Strängen som anges av parametern s tolkas med hjälp NumberStyles.Integer av formatet . Den får inte innehålla några gruppavgränsare eller decimaltecken och får inte ha en decimaldel.

Parametern s parsas med hjälp av formateringsinformationen i ett System.Globalization.NumberFormatInfo objekt som initieras för den aktuella systemkulturen. Mer information finns i NumberFormatInfo.CurrentInfo. Använd metoden för att parsa en sträng med hjälp av formateringsinformationen Parse(String, IFormatProvider) för en viss kultur.

Se även

Gäller för

Parse(String, NumberStyles)

Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs
Källa:
UInt16.cs

Viktigt!

Detta API uppfyller inte CLS.

Konverterar strängrepresentationen av ett tal i ett angivet format till dess 16-bitars osignerade heltalsekvivalent.

Den här metoden är inte CLS-kompatibel. Det CLS-kompatibla alternativet är 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

Parametrar

s
String

En sträng som representerar talet som ska konverteras. Strängen tolkas med hjälp av det format som anges av parametern style .

style
NumberStyles

En bitvis kombination av uppräkningsvärdena som anger det tillåtna formatet för s. Ett typiskt värde att ange är Integer.

Returer

Ett 16-bitars osignerat heltal som motsvarar det tal som anges i s.

Attribut

Undantag

s är null.

style är inte ett NumberStyles värde.

-eller-

style är inte en kombination av AllowHexSpecifier och HexNumber värden.

s är inte i ett format som är kompatibelt med style.

s representerar ett tal som är mindre än UInt16.MinValue eller större än UInt16.MaxValue.

-eller-

s innehåller icke-noll, bråktalssiffror.

Exempel

I följande exempel försöker parsa varje element i en strängmatris med hjälp av ett antal NumberStyles värden.

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

Kommentarer

Parametern style definierar formatelementen (till exempel blanksteg, symbolen för positiva eller negativa tecken, gruppavgränsningssymbolen eller decimaltecknet) som tillåts i parametern s för att parsningsåtgärden ska lyckas. style måste vara en kombination av bitflaggor från NumberStyles uppräkningen. Parametern style gör den här metoden användbar när s den innehåller strängrepresentationen av ett hexadecimalt värde, när talsystemet (decimal eller hexadecimalt) som representeras av s endast är känt vid körning, eller när du vill neka tomt utrymme eller en teckensymbol i s.

Beroende på värdet för stylekan parametern s innehålla följande element:

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

Element inom hakparenteser ([ och ]) är valfria. Om style innehåller NumberStyles.AllowHexSpecifierkan parametern s innehålla följande element:

[ws]hexdigits[ws]

I följande tabell beskrivs varje element.

Element Description
Ws Valfritt blanksteg. Tomt utrymme kan visas i början av s om style innehåller NumberStyles.AllowLeadingWhite flaggan, och det kan visas i slutet av s om style innehåller NumberStyles.AllowTrailingWhite flaggan.
$ En kulturspecifik valutasymbol. Dess position i strängen definieras av NumberFormatInfo.CurrencyNegativePattern egenskaperna och NumberFormatInfo.CurrencyPositivePattern för den aktuella kulturen. Den aktuella kulturens valutasymbol kan visas i s om style den NumberStyles.AllowCurrencySymbol innehåller flaggan.
signera Ett valfritt tecken. Tecknet kan visas i början av s om style innehåller NumberStyles.AllowLeadingSign flaggan, och det kan visas i slutet av s om style innehåller NumberStyles.AllowTrailingSign flaggan. Parenteser kan användas i s för att ange ett negativt värde om style den NumberStyles.AllowParentheses innehåller flaggan. Den negativa teckensymbolen kan dock endast användas med noll. annars genererar metoden en OverflowException.
Siffror

fractional_digits

exponential_digits
En sekvens med siffror från 0 till 9. För fractional_digits är endast siffran 0 giltig.
, En kulturspecifik gruppavgränsare. Den aktuella kulturens gruppavgränsare kan visas i s om style den NumberStyles.AllowThousands innehåller flaggan.
. Ett kulturspecifikt decimaltecken. Den aktuella kulturens decimaltecken kan visas i s om style den NumberStyles.AllowDecimalPoint innehåller flaggan. Endast siffran 0 kan visas som en bråktalssiffra för att parsningsåtgärden ska lyckas. Om fractional_digits innehåller någon annan siffra genereras en FormatException .
E Tecknet "e" eller "E", som anger att värdet representeras i exponentiell (vetenskaplig) notation. Parametern s kan representera ett tal i exponentiell notation om style den NumberStyles.AllowExponent innehåller flaggan.
hexdigits En sekvens med hexadecimala siffror från 0 till f eller 0 till och med F.

Note

Alla avslutande NUL-tecken (U+0000) i s ignoreras av parsningsåtgärden, oavsett argumentets style värde.

En sträng med endast siffror (vilket motsvarar NumberStyles.None formatet) parsar alltid korrekt om den är i typintervallet UInt16 . De flesta av de återstående NumberStyles medlemmarna styr element som kan finnas, men som inte krävs för att finnas, i indatasträngen. Följande tabell visar hur enskilda NumberStyles medlemmar påverkar de element som kan finnas i s.

NumberStyles värde Element som tillåts s utöver siffror
None Endast elementet digits .
AllowDecimalPoint Decimaltecknet (.) och bråksiffriga element.
AllowExponent Tecknet "e" eller "E", som anger exponentiell notation, tillsammans med exponential_digits.
AllowLeadingWhite WS-elementet i början av s.
AllowTrailingWhite WS-elementet i slutet av s.
AllowLeadingSign Teckenelementet i början av s.
AllowTrailingSign Teckenelementet i slutet av s.
AllowParentheses Teckenelementet i form av parenteser som omger det numeriska värdet.
AllowThousands Gruppavgränsaren (,).
AllowCurrencySymbol Valutaelementet ($).
Currency Alla element. Kan dock s inte representera ett hexadecimalt tal eller ett tal i exponentiell notation.
Float WS-elementet i början eller slutet av s, signerar i början av soch decimaltecknet (.). Parametern s kan också använda exponentiell notation.
Number Elementen ws, sign, gruppavgränsare (,) och decimaltecken (.).
Any Alla element. Kan dock s inte representera ett hexadecimalt tal.

Till skillnad från de andra NumberStyles värdena, som tillåter, men inte kräver, innebär förekomsten av vissa formatelement i s, NumberStyles.AllowHexSpecifier att de enskilda numeriska tecknen i s alltid tolkas som hexadecimala tecken. Giltiga hexadecimala tecken är 0-9, A-F och a-f. Ett prefix, till exempel "0x", stöds inte och gör att parsningsåtgärden misslyckas. De enda andra flaggorna som kan kombineras med parametern style är NumberStyles.AllowLeadingWhite och NumberStyles.AllowTrailingWhite. (Uppräkningen NumberStyles innehåller ett sammansatt talformat, NumberStyles.HexNumber, som innehåller båda blankstegsflaggor.)

Note

Om s är strängrepresentationen av ett hexadecimalt tal kan det inte föregås av någon dekoration (till exempel 0x eller &h) som särskiljer det som ett hexadecimalt tal. Detta gör att konverteringen misslyckas.

Parametern s parsas med hjälp av formateringsinformationen i ett NumberFormatInfo objekt som initieras för den aktuella systemkulturen. Om du vill ange den kultur vars formateringsinformation används för parsningsåtgärden anropar du överlagringen Parse(String, NumberStyles, IFormatProvider) .

Se även

Gäller för