UInt32.Parse Méthode

Définition

Convertit la représentation sous forme de chaîne d'un nombre en son équivalent entier non signé 32 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é 32 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é 32 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é 32 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é 32 bits.

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é 32 bits.

Parse(String, NumberStyles, IFormatProvider)

Important

Cette API n’est pas conforme CLS.

Alternative à la conformité CLS
System.Int64.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é 32 bits.

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

Paramètres

s
String

Chaîne représentant 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 indique 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é 32 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 à UInt32.MinValue ou supérieur à UInt32.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 diverses représentations de chaîne de nombres en valeurs entières non signées 32 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 = { "170209", "+170209.0", "+170209,0", "-103214.00",
                                 "-103214,00", "104561.1", "104561,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,
                                    UInt32.Parse(value, style, ci));
               }
               catch (FormatException) {
                  Console.WriteLine("      Unable to parse '{0}'.", value);
               }      
               catch (OverflowException) {
                  Console.WriteLine("      '{0}' is out of range of the UInt32 type.",
                                    value);
               }
            }
         }
      }                                    
   }
}
// The example displays the following output:
//       Parsing strings using the English (United States) culture
//          Style: Integer
//             Converted '170209' to 170209.
//             Unable to parse '+170209.0'.
//             Unable to parse '+170209,0'.
//             Unable to parse '-103214.00'.
//             Unable to parse '-103214,00'.
//             Unable to parse '104561.1'.
//             Unable to parse '104561,1'.
//          Style: Integer, AllowDecimalPoint
//             Converted '170209' to 170209.
//             Converted '+170209.0' to 170209.
//             Unable to parse '+170209,0'.
//             '-103214.00' is out of range of the UInt32 type.
//             Unable to parse '-103214,00'.
//             '104561.1' is out of range of the UInt32 type.
//             Unable to parse '104561,1'.
//       Parsing strings using the French (France) culture
//          Style: Integer
//             Converted '170209' to 170209.
//             Unable to parse '+170209.0'.
//             Unable to parse '+170209,0'.
//             Unable to parse '-103214.00'.
//             Unable to parse '-103214,00'.
//             Unable to parse '104561.1'.
//             Unable to parse '104561,1'.
//          Style: Integer, AllowDecimalPoint
//             Converted '170209' to 170209.
//             Unable to parse '+170209.0'.
//             Converted '+170209,0' to 170209.
//             Unable to parse '-103214.00'.
//             '-103214,00' is out of range of the UInt32 type.
//             Unable to parse '104561.1'.
//             '104561,1' is out of range of the UInt32 type.
open System
open System.Globalization

let cultureNames = [| "en-US"; "fr-FR" |]
let styles = 
    [| NumberStyles.Integer; NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint |]
let values = 
    [| "170209"; "+170209.0"; "+170209,0"; "-103214.00"; "-103214,00"; "104561.1"; "104561,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 {UInt32.Parse(value, style, ci)}."
            with
            | :? FormatException ->
                printfn $"      Unable to parse '{value}'."
            | :? OverflowException ->
                printfn $"      '{value}' is out of range of the UInt32 type."
// The example displays the following output:
//       Parsing strings using the English (United States) culture
//          Style: Integer
//             Converted '170209' to 170209.
//             Unable to parse '+170209.0'.
//             Unable to parse '+170209,0'.
//             Unable to parse '-103214.00'.
//             Unable to parse '-103214,00'.
//             Unable to parse '104561.1'.
//             Unable to parse '104561,1'.
//          Style: Integer, AllowDecimalPoint
//             Converted '170209' to 170209.
//             Converted '+170209.0' to 170209.
//             Unable to parse '+170209,0'.
//             '-103214.00' is out of range of the UInt32 type.
//             Unable to parse '-103214,00'.
//             '104561.1' is out of range of the UInt32 type.
//             Unable to parse '104561,1'.
//       Parsing strings using the French (France) culture
//          Style: Integer
//             Converted '170209' to 170209.
//             Unable to parse '+170209.0'.
//             Unable to parse '+170209,0'.
//             Unable to parse '-103214.00'.
//             Unable to parse '-103214,00'.
//             Unable to parse '104561.1'.
//             Unable to parse '104561,1'.
//          Style: Integer, AllowDecimalPoint
//             Converted '170209' to 170209.
//             Unable to parse '+170209.0'.
//             Converted '+170209,0' to 170209.
//             Unable to parse '-103214.00'.
//             '-103214,00' is out of range of the UInt32 type.
//             Unable to parse '104561.1'.
//             '104561,1' is out of range of the UInt32 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 = { "170209", "+170209.0", "+170209,0", "-103214.00", _
                                 "-103214,00", "104561.1", "104561,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, _
                                    UInt32.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 UInt32 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 '170209' to 170209.
'             Unable to parse '+170209.0'.
'             Unable to parse '+170209,0'.
'             Unable to parse '-103214.00'.
'             Unable to parse '-103214,00'.
'             Unable to parse '104561.1'.
'             Unable to parse '104561,1'.
'          Style: Integer, AllowDecimalPoint
'             Converted '170209' to 170209.
'             Converted '+170209.0' to 170209.
'             Unable to parse '+170209,0'.
'             '-103214.00' is out of range of the UInt32 type.
'             Unable to parse '-103214,00'.
'             '104561.1' is out of range of the UInt32 type.
'             Unable to parse '104561,1'.
'       Parsing strings using the French (France) culture
'          Style: Integer
'             Converted '170209' to 170209.
'             Unable to parse '+170209.0'.
'             Unable to parse '+170209,0'.
'             Unable to parse '-103214.00'.
'             Unable to parse '-103214,00'.
'             Unable to parse '104561.1'.
'             Unable to parse '104561,1'.
'          Style: Integer, AllowDecimalPoint
'             Converted '170209' to 170209.
'             Unable to parse '+170209.0'.
'             Converted '+170209,0' to 170209.
'             Unable to parse '-103214.00'.
'             '-103214,00' is out of range of the UInt32 type.
'             Unable to parse '104561.1'.
'             '104561,1' is out of range of the UInt32 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 seuls autres indicateurs qui peuvent être combinés avec lui 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)

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é 32 bits.

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

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 de bits de valeurs d'énumération qui indique 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é 32 bits équivalant au nombre spécifié dans s.

Implémente

Attributs

S’applique à

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

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

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

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)

Important

Cette API n’est pas conforme CLS.

Alternative à la conformité CLS
System.Int64.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é 32 bits.

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

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é 32 bits équivalant au nombre spécifié dans s.

Implémente

Attributs

Exceptions

s a la valeur null.

Le style de s est incorrect.

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

Exemples

L’exemple suivant est le gestionnaire d’événements click d’un formulaire Web. Il utilise le tableau retourné par la HttpRequest.UserLanguages propriété pour déterminer les paramètres régionaux de l’utilisateur. Il instancie ensuite un CultureInfo objet qui correspond à ces paramètres régionaux. L’objet NumberFormatInfo qui appartient à cet CultureInfo objet est ensuite passé à la Parse(String, IFormatProvider) méthode pour convertir l’entrée de l’utilisateur en valeur UInt32 .

protected void OkToUInteger_Click(object sender, EventArgs e)
{
    string locale;
    uint number;
    CultureInfo culture;

    // Return if string is empty
    if (String.IsNullOrEmpty(this.inputNumber.Text))
        return;

    // Get locale of web request to determine possible format of number
    if (Request.UserLanguages.Length == 0)
        return;
    locale = Request.UserLanguages[0];
    if (String.IsNullOrEmpty(locale))
        return;

    // Instantiate CultureInfo object for the user's locale
    culture = new CultureInfo(locale);

    // Convert user input from a string to a number
    try
    {
        number = UInt32.Parse(this.inputNumber.Text, culture.NumberFormat);
    }
    catch (FormatException)
    {
        return;
    }
    catch (Exception)
    {
        return;
    }
    // Output number to label on web form
    this.outputNumber.Text = "Number is " + number.ToString();
}
Protected Sub OKToUInteger_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OKToUInteger.Click
   Dim locale As String
   Dim culture As CultureInfo
   Dim number As UInteger

   ' Return if string is empty
   If String.IsNullOrEmpty(Me.inputNumber.Text) Then Exit Sub

   ' Get locale of web request to determine possible format of number
   If Request.UserLanguages.Length = 0 Then Exit Sub
   locale = Request.UserLanguages(0)
   If String.IsNullOrEmpty(locale) Then Exit Sub

   ' Instantiate CultureInfo object for the user's locale
   culture = New CultureInfo(locale)

   ' Convert user input from a string to a number
   Try
      number = UInt32.Parse(Me.inputNumber.Text, culture.NumberFormat)
   Catch ex As FormatException
      Exit Sub
   Catch ex As Exception
      Exit Sub
   End Try

   ' Output number to label on web form
   Me.outputNumber.Text = "Number is " & number.ToString()
End Sub

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 entière non signée, 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)

Important

Cette API n’est pas conforme CLS.

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

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

public:
 static System::UInt32 Parse(System::String ^ s, System::Globalization::NumberStyles style);
[System.CLSCompliant(false)]
public static uint Parse (string s, System.Globalization.NumberStyles style);
public static uint Parse (string s, System.Globalization.NumberStyles style);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles -> uint32
static member Parse : string * System.Globalization.NumberStyles -> uint32
Public Shared Function Parse (s As String, style As NumberStyles) As UInteger

Paramètres

s
String

Chaîne représentant 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é 32 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 à UInt32.MinValue ou supérieur à UInt32.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= { " 214309 ", "1,064,181", "(0)", "10241+", " + 21499 ", 
                         " +21499 ", "122153.00", "1e03ff", "91300.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 {
               uint number = UInt32.Parse(value, style);
               Console.WriteLine("   {0}: {1}", style, number);
            }   
            catch (FormatException) {
               Console.WriteLine("   {0}: Bad Format", style);
            }   
            catch (OverflowException)
            {
               Console.WriteLine("   {0}: Overflow", value);         
            }         
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//    Attempting to convert ' 214309 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: 214309
//       Integer, AllowTrailingSign: 214309
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '1,064,181':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: 1064181
//       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 '10241+':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 10241
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' + 21499 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' +21499 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 21499
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '122153.00':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 122153
//    
//    Attempting to convert '1e03ff':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '91300.0e-2':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 913
open System
open System.Globalization

let values = 
    [| " 214309 "; "1,064,181"; "(0)"; "10241+"; " + 21499 " 
       " +21499 "; "122153.00"; "1e03ff"; "91300.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 = UInt32.Parse(value, style)
            printfn $"   {style}: {number}"
        with
        | :? FormatException ->
            printfn $"   {style}: Bad Format"
        | :? OverflowException ->
            printfn $"   {value}: Overflow"
    printfn "" 
// The example displays the following output:
//    Attempting to convert ' 214309 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: 214309
//       Integer, AllowTrailingSign: 214309
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '1,064,181':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: 1064181
//       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 '10241+':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 10241
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' + 21499 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' +21499 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 21499
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '122153.00':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 122153
//    
//    Attempting to convert '1e03ff':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '91300.0e-2':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 913
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim values() As String = { " 214309 ", "1,064,181", "(0)", "10241+", _
                                 " + 21499 ", " +21499 ", "122153.00", _
                                 "1e03ff", "91300.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 UInteger = UInt32.Parse(value, style)
               Console.WriteLine("   {0}: {1}", style, number)
            Catch e As FormatException
               Console.WriteLine("   {0}: Bad Format", style)
            Catch e As OverflowException
               Console.WriteLine("   {0}: Overflow", value)         
            End Try         
         Next
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output:
'    Attempting to convert ' 214309 ':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: 214309
'       Integer, AllowTrailingSign: 214309
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '1,064,181':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: 1064181
'       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 '10241+':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: 10241
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert ' + 21499 ':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert ' +21499 ':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: 21499
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '122153.00':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: 122153
'    
'    Attempting to convert '1e03ff':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '91300.0e-2':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: 913

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 en tant que 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 (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 uniquement (qui correspond au NumberStyles.None style) analyse toujours correctement si elle se trouve dans la plage du UInt32 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 décimaux (.) 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 la 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 s, et le symbole décimal (.). Le s paramètre peut également utiliser la notation exponentielle.
Number Éléments ws, sign, séparateur de groupe (,) et 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 autorisé. 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.)

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)

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

public:
 static System::UInt32 Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<System::UInt32>::Parse;
public static uint Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> uint32
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As UInteger

Paramètres

s
ReadOnlySpan<Char>

Étendue des 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 .s

Implémente

S’applique à

Parse(ReadOnlySpan<Byte>, IFormatProvider)

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

public:
 static System::UInt32 Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<System::UInt32>::Parse;
public static uint Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> uint32
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As UInteger

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 .utf8Text

Implémente

S’applique à

Parse(String)

Important

Cette API n’est pas conforme CLS.

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

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

public:
 static System::UInt32 Parse(System::String ^ s);
[System.CLSCompliant(false)]
public static uint Parse (string s);
public static uint Parse (string s);
[<System.CLSCompliant(false)>]
static member Parse : string -> uint32
static member Parse : string -> uint32
Public Shared Function Parse (s As String) As UInteger

Paramètres

s
String

Chaîne représentant le nombre à convertir.

Retours

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

Attributs

Exceptions

Le paramètre s a la valeur null.

Le format du paramètre s n’est pas correct.

Le s paramètre représente un nombre inférieur à UInt32.MinValue ou supérieur à UInt32.MaxValue.

Exemples

L’exemple suivant utilise la Parse(String) méthode pour analyser un tableau de valeurs de chaîne.

string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127",
                    "0xFA1B", "163042", "-10", "2147483648", 
                    "14065839182", "16e07", "134985.0", "-12034" };
foreach (string value in values)
{
   try {
      uint number = UInt32.Parse(value); 
      Console.WriteLine("{0} --> {1}", value, number);
   }
   catch (FormatException) {
      Console.WriteLine("{0}: Bad Format", value);
   }   
   catch (OverflowException) {
      Console.WriteLine("{0}: Overflow", value);   
   }  
}
// The example displays the following output:
//       +13230 --> 13230
//       -0 --> 0
//       1,390,146: Bad Format
//       $190,235,421,127: Bad Format
//       0xFA1B: Bad Format
//       163042 --> 163042
//       -10: Overflow
//       2147483648 --> 2147483648
//       14065839182: Overflow
//       16e07: Bad Format
//       134985.0: Bad Format
//       -12034: Overflow
open System

let values = 
    [| "+13230"; "-0"; "1,390,146"; "$190,235,421,127"
       "0xFA1B"; "163042"; "-10"; "2147483648"
       "14065839182"; "16e07"; "134985.0"; "-12034" |]

for value in values do
    try
        let number = UInt32.Parse value 
        printfn $"{value} --> {number}"
    with
    | :? FormatException ->
        printfn $"{value}: Bad Format"
    | :? OverflowException ->
        printfn $"{value}: Overflow"
// The example displays the following output:
//       +13230 --> 13230
//       -0 --> 0
//       1,390,146: Bad Format
//       $190,235,421,127: Bad Format
//       0xFA1B: Bad Format
//       163042 --> 163042
//       -10: Overflow
//       2147483648 --> 2147483648
//       14065839182: Overflow
//       16e07: Bad Format
//       134985.0: Bad Format
//       -12034: Overflow
Dim values() As String = { "+13230", "-0", "1,390,146", "$190,235,421,127", 
                           "0xFA1B", "163042", "-10", "2147483648",  
                           "14065839182", "16e07", "134985.0", "-12034" }
For Each value As String In values
   Try
      Dim number As UInteger = UInt32.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}: Overflow", value)   
   End Try  
Next
' The example displays the following output:
'       +13230 --> 13230
'       -0 --> 0
'       1,390,146: Bad Format
'       $190,235,421,127: Bad Format
'       0xFA1B: Bad Format
'       163042 --> 163042
'       -10: Overflow
'       2147483648 --> 2147483648
'       14065839182: Overflow
'       16e07: Bad Format
'       134985.0: Bad Format
'       -12034: Overflow

Remarques

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

[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. 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 de début 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 à