UInt16.Parse Méthode

Définition

Convertit la représentation sous forme de chaîne d'un nombre en son équivalent entier non signé 16 bits.

Surcharges

Parse(String, NumberStyles, IFormatProvider)

Convertit la représentation sous forme de chaîne d'un nombre dans un style et un format propre à la culture spécifiés en son équivalent entier non signé 16 bits.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Convertit la représentation sous forme de plage d'un nombre dans un style et un format propre à la culture spécifiés en son équivalent entier non signé 16 bits.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Analyse une étendue de caractères UTF-8 dans une valeur.

Parse(String, IFormatProvider)

Convertit la représentation sous forme de chaîne d'un nombre dans un format propre à la culture spécifié en son équivalent entier non signé 16 bits.

Parse(String, NumberStyles)

Convertit la représentation sous forme de chaîne d'un nombre dans un style spécifié en son équivalent entier non signé 16 bits.

Cette méthode n’est pas conforme CLS. L’alternative conforme CLS est Parse(String, NumberStyles).

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analyse une étendue de caractères dans une valeur.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Analyse une étendue de caractères UTF-8 dans une valeur.

Parse(String)

Convertit la représentation sous forme de chaîne d'un nombre en son équivalent entier non signé 16 bits.

Parse(String, NumberStyles, IFormatProvider)

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

Important

Cette API n’est pas conforme CLS.

Alternative à la conformité CLS
System.Int32.Parse(String)

Convertit la représentation sous forme de chaîne d'un nombre dans un style et un format propre à la culture spécifiés en son équivalent entier non signé 16 bits.

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

Paramètres

s
String

Chaîne qui représente le nombre à convertir. La chaîne est interprétée à l'aide du style spécifié par le paramètre style.

style
NumberStyles

Combinaison d'opérations de bit des valeurs d'énumération qui indiquent les éléments de style qui peuvent être présents dans s. Une valeur typique à spécifier est Integer.

provider
IFormatProvider

Objet qui fournit des informations de mise en forme propres à la culture sur s.

Retours

Entier non signé 16 bits équivalant au nombre spécifié dans s.

Implémente

Attributs

Exceptions

s a la valeur null.

style n’est pas une valeur NumberStyles.

- ou -

style n’est pas une combinaison des valeurs AllowHexSpecifier et HexNumber.

s n’est pas dans un format compatible avec style.

s représente un nombre inférieur à UInt16.MinValue ou supérieur à UInt16.MaxValue.

- ou -

s inclut des chiffres fractionnaires différents de zéro.

Exemples

L’exemple suivant utilise la Parse(String, NumberStyles, IFormatProvider) méthode pour convertir différentes représentations de chaîne de nombres en valeurs entières non signées 16 bits.

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.

Remarques

Le style paramètre définit les éléments de style (tels que l’espace blanc ou le symbole de signe positif ou négatif) autorisés dans le s paramètre pour que l’opération d’analyse réussisse. Il doit s’agir d’une combinaison d’indicateurs de bits de l’énumération NumberStyles .

Selon la valeur de style, le s paramètre peut inclure les éléments suivants :

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

Les éléments entre crochets ([ et ]) sont facultatifs. Si style inclut NumberStyles.AllowHexSpecifier, le s paramètre peut inclure les éléments suivants :

[ws] hexdigits[ws]

Le tableau suivant décrit chaque élément.

Élément Description
ws Espace blanc facultatif. L’espace blanc peut apparaître au début de s si style inclut l’indicateur NumberStyles.AllowLeadingWhite , et il peut apparaître à la fin de s si style inclut l’indicateur NumberStyles.AllowTrailingWhite .
$ Symbole monétaire spécifique à la culture. Sa position dans la chaîne est définie par la CurrencyPositivePattern propriété de l’objet NumberFormatInfo retourné par la GetFormat méthode du provider paramètre. Le symbole monétaire peut apparaître dans s si style inclut l’indicateur NumberStyles.AllowCurrencySymbol .
sign Signe facultatif. (La méthode lève un OverflowException si s inclut un signe négatif et représente un nombre différent de zéro.) Le signe peut apparaître au début de s si style inclut l’indicateur NumberStyles.AllowLeadingSign , et il peut apparaître à la fin de s si style inclut l’indicateur NumberStyles.AllowTrailingSign . Les parenthèses peuvent être utilisées dans s pour indiquer une valeur négative si style inclut l’indicateur NumberStyles.AllowParentheses .
chiffres Séquence de chiffres comprises entre 0 et 9.
. Symbole décimal spécifique à la culture. Le symbole décimal de la culture actuelle peut apparaître dans s si style inclut l’indicateur NumberStyles.AllowDecimalPoint .
fractional_digits Une ou plusieurs occurrences du chiffre 0 à 9 si style inclut l’indicateur NumberStyles.AllowExponent , ou une ou plusieurs occurrences du chiffre 0 si ce n’est pas le cas. Les chiffres fractionnaires ne peuvent apparaître dans s que si style inclut l’indicateur NumberStyles.AllowDecimalPoint .
E Caractère « e » ou « E », qui indique que la valeur est représentée en notation exponentielle (scientifique). Le s paramètre peut représenter un nombre en notation exponentielle si style inclut l’indicateur NumberStyles.AllowExponent .
exponential_digits Séquence de chiffres comprises entre 0 et 9. Le s paramètre peut représenter un nombre en notation exponentielle si style inclut l’indicateur NumberStyles.AllowExponent .
hexdigits Séquence de chiffres hexadécimaux de 0 à f ou de 0 à F.

Notes

Tous les caractères NUL (U+0000) de fin dans s sont ignorés par l’opération d’analyse, quelle que soit la valeur de l’argument style .

Une chaîne avec des chiffres décimaux uniquement (qui correspond au NumberStyles.None style) analyse toujours correctement. La plupart des membres restants NumberStyles contrôlent les éléments qui peuvent être présents, mais qui ne sont pas obligatoirement présents, dans cette chaîne d’entrée. Le tableau suivant indique comment les membres individuels NumberStyles affectent les éléments qui peuvent être présents dans s.

Valeurs non composites NumberStyles Éléments autorisés en s plus des chiffres
NumberStyles.None Chiffres décimaux uniquement.
NumberStyles.AllowDecimalPoint Éléments décimaux (.) et fractional_digits . Toutefois, si le style n’inclut pas l’indicateur NumberStyles.AllowExponent , fractional_digits ne doit comporter qu’un ou plusieurs chiffres ; sinon, un OverflowException est levée.
NumberStyles.AllowExponent Caractère « e » ou « E », qui indique une notation exponentielle, ainsi que exponential_digits.
NumberStyles.AllowLeadingWhite Élément ws au début de s.
NumberStyles.AllowTrailingWhite Élément ws à la fin de s.
NumberStyles.AllowLeadingSign Signe avant les chiffres.
NumberStyles.AllowTrailingSign Signe après les chiffres.
NumberStyles.AllowParentheses Parenthèses avant et après les chiffres pour indiquer une valeur négative.
NumberStyles.AllowThousands Élément séparateur de groupe (,).
NumberStyles.AllowCurrencySymbol Élément currency ($).

Si l’indicateur NumberStyles.AllowHexSpecifier est utilisé, s doit être une valeur hexadécimale. Les chiffres hexadécimaux valides sont de 0 à 9, de a à f et de A à F. Un préfixe, tel que « 0x », n’est pas pris en charge et entraîne l’échec de l’opération d’analyse. Les seuls autres indicateurs qui peuvent être combinés avec NumberStyles.AllowHexSpecifier sont NumberStyles.AllowLeadingWhite et NumberStyles.AllowTrailingWhite. (L’énumération NumberStyles inclut un style numérique composite, NumberStyles.HexNumber, qui inclut les deux indicateurs d’espace blanc.)

Notes

Si le s paramètre est la représentation sous forme de chaîne d’un nombre hexadécimal, il ne peut pas être précédé d’une décoration (telle que 0x ou &h) qui le différencie en tant que nombre hexadécimal. Cela entraîne l’opération d’analyse de lever une exception.

Le provider paramètre est une IFormatProvider implémentation dont GetFormat la méthode retourne un NumberFormatInfo objet qui fournit des informations spécifiques à la culture sur le format de s. Il existe trois façons d’utiliser le provider paramètre pour fournir des informations de mise en forme personnalisées à l’opération d’analyse :

  • Vous pouvez passer l’objet réel NumberFormatInfo qui fournit des informations de mise en forme. (Son implémentation de GetFormat retourne simplement elle-même.)

  • Vous pouvez passer un CultureInfo objet qui spécifie la culture dont la mise en forme doit être utilisée. Sa NumberFormat propriété fournit des informations de mise en forme.

  • Vous pouvez passer une implémentation personnalisée IFormatProvider . Sa GetFormat méthode doit instancier et renvoyer l’objet NumberFormatInfo qui fournit des informations de mise en forme.

Si provider est null, l’objet NumberFormatInfo de la culture actuelle est utilisé.

Voir aussi

S’applique à

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

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

Important

Cette API n’est pas conforme CLS.

Convertit la représentation sous forme de plage d'un nombre dans un style et un format propre à la culture spécifiés en son équivalent entier non signé 16 bits.

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

Paramètres

s
ReadOnlySpan<Char>

Plage contenant les caractères représentant le nombre à convertir. La plage est interprétée à l'aide du style spécifié par le paramètre style.

style
NumberStyles

Combinaison d'opérations de bit des valeurs d'énumération qui indiquent les éléments de style qui peuvent être présents dans s. Une valeur typique à spécifier est Integer.

provider
IFormatProvider

Objet qui fournit des informations de mise en forme propres à la culture sur s.

Retours

Entier non signé 16 bits équivalant au nombre spécifié dans s.

Implémente

Attributs

S’applique à

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Source:
UInt16.cs
Source:
UInt16.cs

Analyse une étendue de caractères UTF-8 dans une valeur.

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

Paramètres

utf8Text
ReadOnlySpan<Byte>

Étendue de caractères UTF-8 à analyser.

style
NumberStyles

Combinaison de styles numériques au niveau du bit qui peut être présente dans utf8Text.

provider
IFormatProvider

Objet qui fournit des informations de mise en forme propres à la culture concernant utf8Text.

Retours

Résultat de l’analyse .utf8Text

Implémente

S’applique à

Parse(String, IFormatProvider)

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

Important

Cette API n’est pas conforme CLS.

Alternative à la conformité CLS
System.Int32.Parse(String)

Convertit la représentation sous forme de chaîne d'un nombre dans un format propre à la culture spécifié en son équivalent entier non signé 16 bits.

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

Paramètres

s
String

Chaîne qui représente le nombre à convertir.

provider
IFormatProvider

Objet qui fournit des informations de mise en forme propres à la culture sur s.

Retours

Entier non signé 16 bits équivalant au nombre spécifié dans s.

Implémente

Attributs

Exceptions

s a la valeur null.

Le format de s est incorrect.

s représente un nombre inférieur à UInt16.MinValue ou supérieur à UInt16.MaxValue.

Exemples

L’exemple suivant instancie une culture personnalisée qui utilise deux signes plus (++) comme signe positif. Il appelle ensuite la méthode pour analyser un tableau de chaînes à l’aide CultureInfo d’objets qui représentent à la Parse(String, IFormatProvider) fois cette culture personnalisée et la culture invariante.

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.

Remarques

Le s paramètre contient un certain nombre de formes :

[ws] [sign] digits[ws]

Les éléments entre crochets ([ et ]) sont facultatifs. Le tableau suivant décrit chaque élément.

Élément Description
ws Espace blanc facultatif.
sign Signe facultatif ou signe négatif si s représente la valeur zéro.
chiffres Séquence de chiffres compris entre 0 et 9.

Le paramètre s est interprété à l’aide du NumberStyles.Integer style . En plus des chiffres décimaux de la valeur d’octet, seuls les espaces de début et de fin ainsi qu’un signe de début sont autorisés. (Si le signe négatif est présent, s doit représenter une valeur de zéro ou la méthode lève un OverflowException.) Pour définir explicitement les éléments de style avec les informations de mise en forme spécifiques à la culture qui peuvent être présentes dans s, utilisez la Parse(String, NumberStyles, IFormatProvider) méthode .

Le provider paramètre est une IFormatProvider implémentation dont GetFormat la méthode retourne un NumberFormatInfo objet qui fournit des informations spécifiques à la culture sur le format de s. Il existe trois façons d’utiliser le provider paramètre pour fournir des informations de mise en forme personnalisées à l’opération d’analyse :

  • Vous pouvez passer l’objet réel NumberFormatInfo qui fournit des informations de mise en forme. (Son implémentation de GetFormat retourne simplement elle-même.)

  • Vous pouvez passer un CultureInfo objet qui spécifie la culture dont la mise en forme doit être utilisée. Sa NumberFormat propriété fournit des informations de mise en forme.

  • Vous pouvez passer une implémentation personnalisée IFormatProvider . Sa GetFormat méthode doit instancier et renvoyer l’objet NumberFormatInfo qui fournit des informations de mise en forme.

Si provider est null, le NumberFormatInfo pour la culture actuelle est utilisé.

Voir aussi

S’applique à

Parse(String, NumberStyles)

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

Important

Cette API n’est pas conforme CLS.

Convertit la représentation sous forme de chaîne d'un nombre dans un style spécifié en son équivalent entier non signé 16 bits.

Cette méthode n’est pas conforme CLS. L’alternative conforme CLS est 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

Paramètres

s
String

Chaîne qui représente le nombre à convertir. La chaîne est interprétée à l'aide du style spécifié par le paramètre style.

style
NumberStyles

Combinaison de bits de valeurs d'énumération qui spécifie le format autorisé de s. Une valeur typique à spécifier est Integer.

Retours

Entier non signé 16 bits équivalant au nombre spécifié dans s.

Attributs

Exceptions

s a la valeur null.

style n’est pas une valeur NumberStyles.

- ou -

style n’est pas une combinaison des valeurs AllowHexSpecifier et HexNumber.

s n’est pas dans un format compatible avec style.

s représente un nombre inférieur à UInt16.MinValue ou supérieur à UInt16.MaxValue.

- ou -

s inclut des chiffres fractionnaires différents de zéro.

Exemples

L’exemple suivant tente d’analyser chaque élément d’un tableau de chaînes à l’aide d’un certain nombre de NumberStyles valeurs.

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

Remarques

Le style paramètre définit les éléments de style (tels que l’espace blanc, le symbole de signe positif ou négatif, le symbole séparateur de groupe ou le symbole décimal) autorisés dans le s paramètre pour que l’opération d’analyse réussisse. style doit être une combinaison d’indicateurs de bits de l’énumération NumberStyles . Le style paramètre rend cette surcharge de méthode utile lorsque s contient la représentation sous forme de chaîne d’une valeur hexadécimale, lorsque le système de nombres (décimal ou hexadécimal) représenté par s n’est connu qu’au moment de l’exécution, ou lorsque vous souhaitez interdire l’espace blanc ou un symbole de connexion dans s.

Selon la valeur de style, le s paramètre peut inclure les éléments suivants :

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

Les éléments entre crochets ([ et ]) sont facultatifs. Si style inclut NumberStyles.AllowHexSpecifier, le s paramètre peut contenir les éléments suivants :

[ws] hexdigits[ws]

Le tableau suivant décrit chaque élément.

Élément Description
ws Espace blanc facultatif. L’espace blanc peut apparaître au début de s si style inclut l’indicateur NumberStyles.AllowLeadingWhite , et il peut apparaître à la fin de s si style inclut l’indicateur NumberStyles.AllowTrailingWhite .
$ Symbole monétaire spécifique à la culture. Sa position dans la chaîne est définie par les NumberFormatInfo.CurrencyNegativePattern propriétés et NumberFormatInfo.CurrencyPositivePattern de la culture actuelle. Le symbole monétaire de la culture actuelle peut apparaître dans s si style inclut l’indicateur NumberStyles.AllowCurrencySymbol .
sign Signe facultatif. Le signe peut apparaître au début de s si style inclut l’indicateur NumberStyles.AllowLeadingSign , et il peut apparaître à la fin de s si style inclut l’indicateur NumberStyles.AllowTrailingSign . Les parenthèses peuvent être utilisées dans s pour indiquer une valeur négative si style inclut l’indicateur NumberStyles.AllowParentheses . Toutefois, le symbole de signe négatif ne peut être utilisé qu’avec zéro ; sinon, la méthode lève un OverflowException.
chiffres

fractional_digits

exponential_digits
Séquence de chiffres comprises entre 0 et 9. Pour fractional_digits, seul le chiffre 0 est valide.
, Symbole de séparateur de groupe spécifique à la culture. Le séparateur de groupe de la culture actuelle peut apparaître dans s si style inclut l’indicateur NumberStyles.AllowThousands .
. Symbole décimal spécifique à la culture. Le symbole décimal de la culture actuelle peut apparaître dans s si style inclut l’indicateur NumberStyles.AllowDecimalPoint . Seul le chiffre 0 peut apparaître sous la forme d’un chiffre fractionnaire pour que l’opération d’analyse réussisse ; si fractional_digits inclut un autre chiffre, un FormatException est levée.
E Caractère « e » ou « E », qui indique que la valeur est représentée en notation exponentielle (scientifique). Le s paramètre peut représenter un nombre en notation exponentielle si style inclut l’indicateur NumberStyles.AllowExponent .
hexdigits Séquence de chiffres hexadécimaux de 0 à f ou de 0 à F.

Notes

Tous les caractères NUL de fin (U+0000) dans s sont ignorés par l’opération d’analyse, quelle que soit la valeur de l’argument style .

Une chaîne avec des chiffres uniquement (qui correspond au NumberStyles.None style) s’analyse toujours correctement si elle se trouve dans la plage du UInt16 type. La plupart des membres restants NumberStyles contrôlent les éléments qui peuvent être présents, mais qui ne sont pas obligatoirement présents, dans la chaîne d’entrée. Le tableau suivant indique comment les membres individuels NumberStyles affectent les éléments qui peuvent être présents dans s.

Valeur NumberStyles Éléments autorisés en s plus des chiffres
None Élément digits uniquement.
AllowDecimalPoint Éléments à virgule décimale (.) et à chiffres fractionnaires .
AllowExponent Caractère « e » ou « E », qui indique une notation exponentielle, ainsi que exponential_digits.
AllowLeadingWhite Élément ws au début de s.
AllowTrailingWhite Élément ws à la fin de s.
AllowLeadingSign Élément sign au début de s.
AllowTrailingSign Élément sign à la fin de s.
AllowParentheses Élément sign sous forme de parenthèses englobant la valeur numérique.
AllowThousands Élément séparateur de groupe (,).
AllowCurrencySymbol Élément currency ($).
Currency Tous les éléments. Toutefois, s ne peut pas représenter un nombre hexadécimal ou un nombre en notation exponentielle.
Float L’élément ws au début ou à la fin de s, signe au début de set le symbole décimal (.). Le s paramètre peut également utiliser la notation exponentielle.
Number Éléments ws, sign, séparateur de groupe (,) et virgule décimale (.).
Any Tous les éléments. Toutefois, s ne peut pas représenter un nombre hexadécimal.

Contrairement aux autres NumberStyles valeurs, qui autorisent, mais n’exigent pas, la présence d’éléments de style particuliers dans s, la valeur de NumberStyles.AllowHexSpecifier style signifie que les caractères numériques individuels dans s sont toujours interprétés comme des caractères hexadécimaux. Les caractères hexadécimaux valides sont 0-9, A-F et a-f. Un préfixe, tel que « 0x », n’est pas pris en charge et provoque l’échec de l’opération d’analyse. Les seuls autres indicateurs qui peuvent être combinés avec le style paramètre sont NumberStyles.AllowLeadingWhite et NumberStyles.AllowTrailingWhite. (L’énumération NumberStyles inclut un style numérique composite, NumberStyles.HexNumber, qui inclut les deux indicateurs d’espace blanc.)

Notes

Si s est la représentation sous forme de chaîne d’un nombre hexadécimal, elle ne peut pas être précédée d’une décoration (telle que 0x ou &h) qui le différencie en tant que nombre hexadécimal. Cela entraîne l’échec de la conversion.

Le s paramètre est analysé à l’aide des informations de mise en forme dans un NumberFormatInfo objet initialisé pour la culture système actuelle. Pour spécifier la culture dont les informations de mise en forme sont utilisées pour l’opération d’analyse, appelez la Parse(String, NumberStyles, IFormatProvider) surcharge.

Voir aussi

S’applique à

Parse(ReadOnlySpan<Char>, IFormatProvider)

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

Analyse une étendue de caractères dans une valeur.

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

Paramètres

s
ReadOnlySpan<Char>

Étendue de caractères à analyser.

provider
IFormatProvider

Objet qui fournit des informations de mise en forme propres à la culture concernant s.

Retours

Résultat de l’analyse de s.

Implémente

S’applique à

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Source:
UInt16.cs
Source:
UInt16.cs

Analyse une étendue de caractères UTF-8 dans une valeur.

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

Paramètres

utf8Text
ReadOnlySpan<Byte>

Étendue de caractères UTF-8 à analyser.

provider
IFormatProvider

Objet qui fournit des informations de mise en forme propres à la culture concernant utf8Text.

Retours

Résultat de l’analyse de utf8Text.

Implémente

S’applique à

Parse(String)

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

Important

Cette API n’est pas conforme CLS.

Alternative à la conformité CLS
System.Int32.Parse(String)

Convertit la représentation sous forme de chaîne d'un nombre en son équivalent entier non signé 16 bits.

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

Paramètres

s
String

Chaîne qui représente le nombre à convertir.

Retours

Entier non signé 16 bits équivalent au nombre contenu dans s.

Attributs

Exceptions

s a la valeur null.

Le format de s est incorrect.

s représente un nombre inférieur à UInt16.MinValue ou supérieur à UInt16.MaxValue.

Exemples

L’exemple suivant appelle la Parse(String) méthode pour convertir chaque élément d’un tableau de chaînes en entier 16 bits non signé.

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

Remarques

Le s paramètre doit être la représentation sous forme de chaîne d’un nombre sous la forme suivante.

[ws] [signe] digits[ws]

Les éléments entre crochets ([ et ]) sont facultatifs. Le tableau suivant décrit chaque élément.

Élément Description
ws Espace blanc facultatif.
sign Signe facultatif. Les caractères de signe valides sont déterminés par les NumberFormatInfo.NegativeSign propriétés et NumberFormatInfo.PositiveSign de la culture actuelle. Toutefois, le symbole de signe négatif ne peut être utilisé qu’avec zéro ; sinon, la méthode lève un OverflowException.
chiffres Séquence de chiffres compris entre 0 et 9. Tous les zéros non significatifs sont ignorés.

Notes

La chaîne spécifiée par le paramètre est interprétée à l’aide s du NumberStyles.Integer style . Il ne peut pas contenir de séparateurs de groupe ou de séparateur décimal, et il ne peut pas avoir de partie décimale.

Le s paramètre est analysé à l’aide des informations de mise en forme dans un System.Globalization.NumberFormatInfo objet initialisé pour la culture système actuelle. Pour plus d'informations, consultez NumberFormatInfo.CurrentInfo. Pour analyser une chaîne à l’aide des informations de mise en forme d’une culture spécifique, utilisez la Parse(String, IFormatProvider) méthode .

Voir aussi

S’applique à