UInt32.Parse Método

Definição

Converte a representação de cadeia de caracteres de um número em seu inteiro sem sinal de 32 bits equivalente.

Sobrecargas

Parse(String, NumberStyles, IFormatProvider)

Converte a representação de cadeia de caracteres de um número em um formato específico à cultura e estilo especificados no seu inteiro sem sinal de 32 bits equivalente.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Converte a representação de intervalo de um número em um formato específico da cultura e estilo especificados em seu inteiro sem sinal de 32 bits equivalente.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Analisa um intervalo de caracteres UTF-8 em um valor.

Parse(String, IFormatProvider)

Converte a representação de cadeia de caracteres de um número em um formato específico à cultura especificado no seu inteiro sem sinal de 32 bits equivalente.

Parse(String, NumberStyles)

Converte a representação de cadeia de caracteres de um número em um estilo especificado em um inteiro sem sinal de 32 bits equivalente.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analisa um intervalo de caracteres em um valor.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Analisa um intervalo de caracteres UTF-8 em um valor.

Parse(String)

Converte a representação de cadeia de caracteres de um número em seu inteiro sem sinal de 32 bits equivalente.

Parse(String, NumberStyles, IFormatProvider)

Origem:
UInt32.cs
Origem:
UInt32.cs
Origem:
UInt32.cs

Importante

Esta API não está em conformidade com CLS.

Alternativa em conformidade com CLS
System.Int64.Parse(String)

Converte a representação de cadeia de caracteres de um número em um formato específico à cultura e estilo especificados no seu inteiro sem sinal de 32 bits equivalente.

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

Parâmetros

s
String

Uma cadeia de caracteres que representa o número a ser convertido. A cadeia de caracteres é interpretada usando-se o estilo especificado pelo parâmetro style.

style
NumberStyles

Um combinação bit a bit de valores de enumeração que indica os elementos de estilo que podem estar presentes em s. Um valor típico a ser especificado é Integer.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura sobre s.

Retornos

Um inteiro sem sinal de 32 bits equivalente ao número especificado em s.

Implementações

Atributos

Exceções

style não é um valor NumberStyles.

- ou -

style não é uma combinação de valores AllowHexSpecifier e HexNumber.

s não está em um formato em conformidade com style.

s representa um número menor que UInt32.MinValue ou maior que UInt32.MaxValue.

- ou -

s inclui dígitos fracionários, diferentes de zero.

Exemplos

O exemplo a seguir usa o Parse(String, NumberStyles, IFormatProvider) método para converter várias representações de cadeia de caracteres de números em valores inteiros sem sinal de 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.

Comentários

O parâmetro style define os elementos de estilo (como o espaço em branco ou o símbolo de sinal positivo ou negativo) que são permitidos no parâmetro s para que a operação de análise seja bem-sucedida. Ele deve ser uma combinação de sinalizadores de bits da enumeração NumberStyles.

Dependendo do valor de style, o parâmetro s pode incluir os seguintes elementos:

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

Os elementos entre colchetes ([ e ]) são opcionais. Se style incluir NumberStyles.AllowHexSpecifier, o s parâmetro poderá incluir os seguintes elementos:

[ws] hexdigits[ws]

A tabela a seguir descreve cada elemento.

Elemento Descrição
ws Espaço em branco opcional. Espaço em branco pode ser exibido no início de s caso style inclua o sinalizador NumberStyles.AllowLeadingWhite e pode ser exibido no final de s caso style inclua o sinalizador NumberStyles.AllowTrailingWhite.
$ Um símbolo de moeda específico de cultura. Sua posição na cadeia de caracteres é definida pela CurrencyPositivePattern propriedade do NumberFormatInfo objeto que é retornado pelo GetFormat método do provider parâmetro . O símbolo de moeda pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowCurrencySymbol.
sign Um sinal opcional. (O método lança um OverflowException se s inclui um sinal negativo e representa um número diferente de zero.) O sinal pode aparecer no início de s se incluir o NumberStyles.AllowLeadingSign sinalizador e pode aparecer no final de s se style incluir o NumberStyles.AllowTrailingSignstyle sinalizador. Os parênteses podem ser usados em s para indicar um valor negativo caso style inclua o sinalizador NumberStyles.AllowParentheses.
dígitos Uma sequência de dígitos de 0 a 9.
. Um símbolo de vírgula decimal específico de cultura. O símbolo da vírgula decimal da cultura atual pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowDecimalPoint.
Fractional_digits Uma ou mais ocorrências do dígito 0-9 caso style inclua o sinalizador NumberStyles.AllowExponent ou uma ou mais ocorrências do dígito 0 do contrário. Os dígitos fracionários só podem ser exibidos em s caso style inclua o sinalizador NumberStyles.AllowDecimalPoint.
E O caractere "e" ou "E", que indica que o valor é representado em notação exponencial (científica). O parâmetro s pode representar um número em notação exponencial caso style inclua o sinalizador NumberStyles.AllowExponent.
exponential_digits Uma sequência de dígitos de 0 a 9. O parâmetro s pode representar um número em notação exponencial caso style inclua o sinalizador NumberStyles.AllowExponent.
hexdigits Uma sequência de dígitos hexadecimais de 0 a f ou de 0 a F.

Observação

Todos os caracteres NUL de terminação (U+0000) no s são ignorados pela operação de análise, independentemente do valor do style argumento.

Uma cadeia de caracteres apenas com dígitos decimais (que corresponde ao estilo NumberStyles.None ) sempre é analisada com êxito. A maioria dos elementos de controle de membros NumberStyles restantes que podem estar presentes, mas que não precisam estar presentes, na cadeia de caracteres de entrada. A tabela a seguir indica como os membros NumberStyles individuais afetam os elementos que podem estar presentes em s.

Valores NumberStyles não compostos Elementos permitidos em s além de dígitos
NumberStyles.None Somente dígitos decimais.
NumberStyles.AllowDecimalPoint O ponto decimal (.) e fractional_digits elementos. No entanto, se o estilo não incluir o NumberStyles.AllowExponent sinalizador, fractional_digits deverá consistir em apenas um ou mais 0 dígitos; caso contrário, um OverflowException será gerado.
NumberStyles.AllowExponent O caractere "e" ou "E", que indica notação exponencial, juntamente com exponential_digits.
NumberStyles.AllowLeadingWhite O elemento ws no início de s.
NumberStyles.AllowTrailingWhite O elemento ws no final de s.
NumberStyles.AllowLeadingSign Um sinal antes dos dígitos.
NumberStyles.AllowTrailingSign Um sinal após dígitos.
NumberStyles.AllowParentheses Parênteses antes e depois dos dígitos para indicar um valor negativo.
NumberStyles.AllowThousands O elemento separador de grupo (,).
NumberStyles.AllowCurrencySymbol O elemento currency ($).

Caso o sinalizador NumberStyles.AllowHexSpecifier seja usado, s deve ser um valor hexadecimal. O único outros sinalizadores que podem ser combinados com ele são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A enumeração de NumberStyles inclui um estilo de número composto, NumberStyles.HexNumber, que inclui ambos os sinalizadores de espaço em branco.)

Observação

Caso o parâmetro s seja a representação da cadeia de caracteres de um número hexadecimal, ele não pode ser precedido por uma decoração (como 0x ou &h) que o diferencia como um número hexadecimal. Isso faz a operação de análise lançar uma exceção.

O parâmetro provider é uma implementação de IFormatProvider cujo método GetFormat retorna um objeto NumberFormatInfo que fornece informações de cultura específica sobre o formato de s. Existem três maneiras de usar o parâmetro provider para fornecer informações de formatação personalizadas para a operação de análise:

  • É possível passar o objeto real NumberFormatInfo que fornece informações de formatação. (Sua implementação de GetFormat retorna apenas ele próprio.)

  • É possível passar um objeto CultureInfo que especifica a cultura cuja formatação deve ser usada. A propriedade NumberFormat fornece informações de formatação.

  • É possível passar uma implementação de IFormatProvider personalizada. O método GetFormat deve criar uma instância e retornar o objeto NumberFormatInfo que fornece informações de formatação.

Caso provider seja null, o objeto NumberFormatInfo da cultura atual é usado.

Confira também

Aplica-se a

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Origem:
UInt32.cs
Origem:
UInt32.cs
Origem:
UInt32.cs

Importante

Esta API não está em conformidade com CLS.

Converte a representação de intervalo de um número em um formato específico da cultura e estilo especificados em seu inteiro sem sinal de 32 bits equivalente.

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

Parâmetros

s
ReadOnlySpan<Char>

Um intervalo que contém os caracteres que representam o número a ser convertido. O intervalo é interpretado usando o estilo especificado pelo parâmetro style.

style
NumberStyles

Um combinação bit a bit de valores de enumeração que indica os elementos de estilo que podem estar presentes em s. Um valor típico a ser especificado é Integer.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura sobre s.

Retornos

Um inteiro sem sinal de 32 bits equivalente ao número especificado em s.

Implementações

Atributos

Aplica-se a

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Origem:
UInt32.cs
Origem:
UInt32.cs

Analisa um intervalo de caracteres UTF-8 em um valor.

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

Parâmetros

utf8Text
ReadOnlySpan<Byte>

O intervalo de caracteres UTF-8 a serem analisados.

style
NumberStyles

Uma combinação bit a bit de estilos numéricos que podem estar presentes em utf8Text.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas à cultura sobre utf8Text.

Retornos

O resultado da análise utf8Text.

Implementações

Aplica-se a

Parse(String, IFormatProvider)

Origem:
UInt32.cs
Origem:
UInt32.cs
Origem:
UInt32.cs

Importante

Esta API não está em conformidade com CLS.

Alternativa em conformidade com CLS
System.Int64.Parse(String)

Converte a representação de cadeia de caracteres de um número em um formato específico à cultura especificado no seu inteiro sem sinal de 32 bits equivalente.

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

Parâmetros

s
String

Uma cadeia de caracteres que representa o número a ser convertido.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura sobre s.

Retornos

Um inteiro sem sinal de 32 bits equivalente ao número especificado em s.

Implementações

Atributos

Exceções

s não está no estilo correto.

s representa um número menor que UInt32.MinValue ou maior que UInt32.MaxValue.

Exemplos

O exemplo a seguir é o manipulador de eventos de clique do botão de um formulário da Web. Ele usa a matriz retornada pela propriedade HttpRequest.UserLanguages para determinar a localidade do usuário. Em seguida, ele instancia um objeto CultureInfo que corresponde à localidade. O NumberFormatInfo objeto que pertence a esse CultureInfo objeto é então passado para o Parse(String, IFormatProvider) método para converter a entrada do usuário em um UInt32 valor.

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

Comentários

O parâmetro s contém um número da forma:

[ws] [sign] digits[ws]

Itens entre colchetes ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.

Elemento Descrição
ws Espaço em branco opcional.
sign Um sinal opcional ou um sinal negativo se s representar o valor zero.
dígitos Uma sequência de dígitos que varia de 0 a 9.

O parâmetro s é interpretado usando o NumberStyles.Integer estilo . Além dos dígitos decimais do valor inteiro sem sinal, somente espaços à esquerda e à direita, juntamente com um sinal à esquerda, são permitidos. (Se o sinal negativo estiver presente, s deverá representar um valor igual a zero ou o método gerará um OverflowException.) Para definir explicitamente os elementos de estilo junto com as informações de formatação específicas da cultura que podem estar presentes no s, use o Parse(String, NumberStyles, IFormatProvider) método .

O parâmetro provider é uma implementação de IFormatProvider cujo método GetFormat retorna um objeto NumberFormatInfo que fornece informações de cultura específica sobre o formato de s. Existem três maneiras de usar o parâmetro provider para fornecer informações de formatação personalizadas para a operação de análise:

  • É possível passar o objeto real NumberFormatInfo que fornece informações de formatação. (Sua implementação de GetFormat retorna apenas ele próprio.)

  • É possível passar um objeto CultureInfo que especifica a cultura cuja formatação deve ser usada. A propriedade NumberFormat fornece informações de formatação.

  • É possível passar uma implementação de IFormatProvider personalizada. O método GetFormat deve criar uma instância e retornar o objeto NumberFormatInfo que fornece informações de formatação.

Caso provider seja null, NumberFormatInfo da cultura atual é usado.

Confira também

Aplica-se a

Parse(String, NumberStyles)

Origem:
UInt32.cs
Origem:
UInt32.cs
Origem:
UInt32.cs

Importante

Esta API não está em conformidade com CLS.

Alternativa em conformidade com CLS
System.Int64.Parse(String)

Converte a representação de cadeia de caracteres de um número em um estilo especificado em um inteiro sem sinal de 32 bits equivalente.

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

Parâmetros

s
String

Uma cadeia de caracteres que representa o número a ser convertido. A cadeia de caracteres é interpretada usando-se o estilo especificado pelo parâmetro style.

style
NumberStyles

Um combinação bit a bit de valores de enumeração que especificam o formato permitido de s. Um valor típico a ser especificado é Integer.

Retornos

Um inteiro sem sinal de 32 bits equivalente ao número especificado em s.

Atributos

Exceções

style não é um valor NumberStyles.

- ou -

style não é uma combinação de valores AllowHexSpecifier e HexNumber.

s não está em um formato em conformidade com style.

s representa um número menor que UInt32.MinValue ou maior que UInt32.MaxValue.

- ou -

s inclui dígitos fracionários, diferentes de zero.

Exemplos

O exemplo a seguir tenta analisar cada elemento em uma matriz de cadeia de caracteres usando vários NumberStyles valores.

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

Comentários

O style parâmetro define os elementos de estilo (como espaço em branco, o símbolo de sinal positivo ou negativo, o símbolo separador de grupo ou o símbolo de ponto decimal) que são permitidos no s parâmetro para que a operação de análise tenha êxito. style deve ser uma combinação de sinalizadores de bits da NumberStyles enumeração . O style parâmetro torna essa sobrecarga de método útil quando s contém a representação de cadeia de caracteres de um valor hexadecimal, quando o sistema de números (decimal ou hexadecimal) representado por s é conhecido apenas em tempo de execução ou quando você deseja não permitir espaço em branco ou um símbolo de sinal no s.

Dependendo do valor de style, o parâmetro s pode incluir os seguintes elementos:

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

Os elementos entre colchetes ([ e ]) são opcionais. Caso style inclua NumberStyles.AllowHexSpecifier, o parâmetro s pode conter os seguintes elementos:

[ws] hexdigits[ws]

A tabela a seguir descreve cada elemento.

Elemento Descrição
ws Espaço em branco opcional. O espaço em branco pode aparecer no início de s se incluir o NumberStyles.AllowLeadingWhite sinalizador e ele pode aparecer no final de s se style incluir o NumberStyles.AllowTrailingWhitestyle sinalizador.
$ Um símbolo de moeda específico de cultura. A posição na cadeia de caracteres é definida pelas propriedades NumberFormatInfo.CurrencyNegativePattern e NumberFormatInfo.CurrencyPositivePattern da cultura atual. O símbolo de moeda da cultura atual pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowCurrencySymbol.
sign Um sinal opcional. O sinal pode ser exibido no início de s caso style inclua o sinalizador NumberStyles.AllowLeadingSign e ele pode ser exibido no final de s caso style inclua o sinalizador NumberStyles.AllowTrailingSign. Os parênteses podem ser usados em s para indicar um valor negativo caso style inclua o sinalizador NumberStyles.AllowParentheses. No entanto, o símbolo de sinal negativo só pode ser usado com zero; do contrário, o método lança um OverflowException.
dígitos

Fractional_digits

exponential_digits
Uma sequência de dígitos de 0 a 9. Para fractional_digits, somente o dígito 0 é válido.
, Um símbolo de separador do grupo específico da cultura. O separador de grupo da cultura atual poderá aparecer em s se style incluir o NumberStyles.AllowThousands sinalizador.
. Um símbolo de vírgula decimal específico de cultura. O símbolo da vírgula decimal da cultura atual pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowDecimalPoint. Somente o dígito 0 pode aparecer como um dígito fracionário para que a operação de análise tenha êxito; se fractional_digits incluir qualquer outro dígito, um FormatException será gerado.
E O caractere "e" ou "E", que indica que o valor é representado em notação exponencial (científica). O parâmetro s pode representar um número em notação exponencial caso style inclua o sinalizador NumberStyles.AllowExponent.
hexdigits Uma sequência de dígitos hexadecimais de 0 a f ou de 0 a F.

Observação

Todos os caracteres NUL de terminação (U+0000) em s são ignorados pela operação de análise, independentemente do valor do style argumento.

Uma cadeia de caracteres apenas com dígitos (que corresponde ao estilo NumberStyles.None ) sempre é analisada com UInt32 êxito. A maioria dos elementos de controle de membros NumberStyles restantes que podem estar presentes, mas que não precisam estar presentes, na cadeia de caracteres de entrada. A tabela a seguir indica como os membros NumberStyles individuais afetam os elementos que podem estar presentes em s.

NumberStyles valor Elementos permitidos em s além de dígitos
None Somente o elemento de dígitos .
AllowDecimalPoint Os elementos de ponto decimal (.) e dígitos fracionários .
AllowExponent O caractere "e" ou "E", que indica notação exponencial, juntamente com exponential_digits.
AllowLeadingWhite O elemento ws no início de s.
AllowTrailingWhite O elemento ws no final de s.
AllowLeadingSign O elemento sign no início de s.
AllowTrailingSign O elemento sinal no final de s.
AllowParentheses O elemento sinal na forma de parênteses que incluem o valor numérico.
AllowThousands O elemento separador do grupo (,).
AllowCurrencySymbol O elemento de moeda ($).
Currency Todos os elementos. No entanto, s não pode representar um número hexadecimal ou um número em notação exponencial.
Float O elemento ws no início ou no final de s, assina no início de se o símbolo de ponto decimal (.). O parâmetro s também pode usar notação exponencial.
Number Os wselementos , sign, separador de grupo (,) e ponto decimal (.).
Any Todos os elementos. No entanto, s não pode representar um número hexadecimal.

Ao contrário dos outros NumberStyles valores, que permitem, mas não exigem, a presença de elementos de estilo específicos em s, o valor de NumberStyles.AllowHexSpecifier estilo significa que os caracteres numéricos individuais em s são sempre interpretados como caracteres hexadecimais. Os caracteres hexadecimais válidos são 0-9, A-F e a-f. Um prefixo, como "0x", não é permitido. Os únicos outros sinalizadores que podem ser combinados com o parâmetro style são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A enumeração de NumberStyles inclui um estilo de número composto, NumberStyles.HexNumber, que inclui ambos os sinalizadores de espaço em branco.)

Os únicos outros sinalizadores que podem ser combinados com o parâmetro style são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A enumeração de NumberStyles inclui um estilo de número composto, NumberStyles.HexNumber, que inclui ambos os sinalizadores de espaço em branco.)

Observação

Caso s seja a representação da cadeia de caracteres de um número hexadecimal, ele não pode ser precedido por qualquer decoração (como 0x ou &h) que o diferencia como um número hexadecimal. Isso faz a conversão falhar.

O parâmetro s é analisado usando-se as informações de formatação em um objeto NumberFormatInfo que é inicializado para a cultura do sistema atual. Para especificar a cultura cujas informações de formatação são usadas para a operação de análise, chame a Parse(String, NumberStyles, IFormatProvider) sobrecarga.

Confira também

Aplica-se a

Parse(ReadOnlySpan<Char>, IFormatProvider)

Origem:
UInt32.cs
Origem:
UInt32.cs
Origem:
UInt32.cs

Analisa um intervalo de caracteres em um valor.

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

Parâmetros

s
ReadOnlySpan<Char>

O intervalo de caracteres a serem analisados.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas à cultura sobre s.

Retornos

O resultado da análise de s.

Implementações

Aplica-se a

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Origem:
UInt32.cs
Origem:
UInt32.cs

Analisa um intervalo de caracteres UTF-8 em um valor.

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

Parâmetros

utf8Text
ReadOnlySpan<Byte>

O intervalo de caracteres UTF-8 a serem analisados.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas à cultura sobre utf8Text.

Retornos

O resultado da análise de utf8Text.

Implementações

Aplica-se a

Parse(String)

Origem:
UInt32.cs
Origem:
UInt32.cs
Origem:
UInt32.cs

Importante

Esta API não está em conformidade com CLS.

Alternativa em conformidade com CLS
System.Int64.Parse(String)

Converte a representação de cadeia de caracteres de um número em seu inteiro sem sinal de 32 bits equivalente.

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

Parâmetros

s
String

Uma cadeia de caracteres que representa o número a ser convertido.

Retornos

Um inteiro sem sinal de 32 bits equivalente ao número contido em s.

Atributos

Exceções

O parâmetro s é null.

O parâmetro s não tem o formato correto.

O s parâmetro representa um número menor que UInt32.MinValue ou maior que UInt32.MaxValue.

Exemplos

O exemplo a seguir usa o Parse(String) método para analisar uma matriz de valores de cadeia de caracteres.

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

Comentários

O s parâmetro deve ser a representação de cadeia de caracteres de um número no formulário a seguir.

[ws] [sign] digits[ws]

Os elementos entre colchetes ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.

Elemento Descrição
ws Espaço em branco opcional.
sign Um sinal opcional. Os caracteres de sinal válido são determinados pelas propriedades NumberFormatInfo.NegativeSign e NumberFormatInfo.PositiveSign da cultura atual. No entanto, o símbolo de sinal negativo só pode ser usado com zero; do contrário, o método lança um OverflowException.
dígitos Uma sequência de dígitos que varia de 0 a 9. Todos os zeros à esquerda são ignorados.

Observação

A cadeia de caracteres especificada pelo s parâmetro é interpretada usando o NumberStyles.Integer estilo . Ele não pode conter nenhum separador de grupo ou decimal, e não pode ter uma parte decimal.

O parâmetro s é analisado usando-se as informações de formatação em um objeto System.Globalization.NumberFormatInfo que é inicializado para a cultura do sistema atual. Para obter mais informações, consulte NumberFormatInfo.CurrentInfo. Para analisar uma cadeia de caracteres usando as informações de formatação de uma cultura específica, use o Parse(String, IFormatProvider) método .

Confira também

Aplica-se a