Partilhar via


UInt32.Parse Método

Definição

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

Sobrecargas

Nome Description
Parse(String, NumberStyles, IFormatProvider)

Converte a representação de cadeia de caracteres de um número em um formato específico de cultura e estilo especificado em 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 de estilo e cultura especificado 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 em seu 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 equivalente inteiro sem sinal de 32 bits.

Parse(String, NumberStyles)

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

Parse(String, NumberStyles, IFormatProvider)

Origem:
UInt32.cs
Origem:
UInt32.cs
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 de cultura e estilo especificado em 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 o estilo especificado pelo style parâmetro.

style
NumberStyles

Uma 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 NumberStyles valor.

-ou-

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

s não está em um formato compatível com style.

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

-ou-

s inclui dígitos não zero e fracionários.

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

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

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

Elementos em 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. O espaço em branco pode aparecer no início de s se incluir o NumberStyles.AllowLeadingWhite sinalizador e pode aparecer no final de s se style incluir o NumberStyles.AllowTrailingWhitestyle sinalizador.
$ Um símbolo de moeda específico à cultura. Sua posição na cadeia de caracteres é definida pela CurrencyPositivePattern propriedade do NumberFormatInfo objeto que é retornada pelo GetFormat método do provider parâmetro. O símbolo de moeda poderá aparecer s se style incluir o NumberStyles.AllowCurrencySymbol sinalizador.
assinar 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. Parênteses podem ser usados s para indicar um valor negativo se style incluir o NumberStyles.AllowParentheses sinalizador.
Dígitos Uma sequência de dígitos de 0 a 9.
. Um símbolo de ponto decimal específico da cultura. O símbolo de ponto decimal da cultura atual poderá aparecer s se style incluir o NumberStyles.AllowDecimalPoint sinalizador.
Fractional_digits Uma ou mais ocorrências do dígito 0-9 se style incluir o NumberStyles.AllowExponent sinalizador ou uma ou mais ocorrências do dígito 0 se não o fizer. Dígitos fracionários só poderão aparecer s se style incluir o NumberStyles.AllowDecimalPoint sinalizador.
E O caractere "e" ou "E", que indica que o valor é representado na notação exponencial (científica). O s parâmetro pode representar um número na notação exponencial se style incluir o NumberStyles.AllowExponent sinalizador.
exponential_digits Uma sequência de dígitos de 0 a 9. O s parâmetro pode representar um número na notação exponencial se style incluir o NumberStyles.AllowExponent sinalizador.
hexdigits Uma sequência de dígitos hexadecimal de 0 a f ou 0 a F.

Nota

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

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

Valores não compostos NumberStyles Elementos permitidos s além de dígitos
NumberStyles.None Somente dígitos decimais.
NumberStyles.AllowDecimalPoint O ponto decimal (.) e os elementos fractional_digits. 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 ($).

Se o NumberStyles.AllowHexSpecifier sinalizador for usado, s deverá ser um valor hexadecimal. Os únicos outros sinalizadores que podem ser combinados com ele são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A NumberStyles enumeração inclui um estilo de número composto, NumberStyles.HexNumberque inclui sinalizadores de espaço em branco.)

Nota

Se o s parâmetro for a representação de cadeia de caracteres de um número hexadecimal, ele não poderá ser precedido por qualquer decoração (como 0x ou &h) que a diferencie como um número hexadecimal. Isso faz com que a operação de análise gere uma exceção.

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

  • Você pode passar o objeto real NumberFormatInfo que fornece informações de formatação. (Sua implementação de GetFormat simplesmente retorna a si mesma.)

  • Você pode passar um CultureInfo objeto que especifica a cultura cuja formatação deve ser usada. Sua NumberFormat propriedade fornece informações de formatação.

  • Você pode passar uma implementação personalizada IFormatProvider . Seu GetFormat método deve instanciar e retornar o NumberFormatInfo objeto que fornece informações de formatação.

Se provider for null, o NumberFormatInfo objeto para a cultura atual será usado.

Confira também

Aplica-se a

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Origem:
UInt32.cs
Origem:
UInt32.cs
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 de estilo e cultura especificado 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 style parâmetro.

style
NumberStyles

Uma 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
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 da 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
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 em 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 de botão de um formulário da Web. Ele usa a matriz retornada pela HttpRequest.UserLanguages propriedade para determinar a localidade do usuário. Em seguida, cria uma instância de um CultureInfo objeto que corresponde a essa 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 s parâmetro contém um número do formulário:

[ws][sign]digits[ws]

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

Elemento Descrição
Ws Espaço em branco opcional.
assinar Um sinal opcional ou um sinal negativo se s representar o valor zero.
Dígitos Uma sequência de dígitos variando 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 s, use o Parse(String, NumberStyles, IFormatProvider) método.

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

  • Você pode passar o objeto real NumberFormatInfo que fornece informações de formatação. (Sua implementação de GetFormat simplesmente retorna a si mesma.)

  • Você pode passar um CultureInfo objeto que especifica a cultura cuja formatação deve ser usada. Sua NumberFormat propriedade fornece informações de formatação.

  • Você pode passar uma implementação personalizada IFormatProvider . Seu GetFormat método deve instanciar e retornar o NumberFormatInfo objeto que fornece informações de formatação.

Se provider for null, o NumberFormatInfo para a cultura atual é usado.

Confira também

Aplica-se a

Parse(ReadOnlySpan<Char>, IFormatProvider)

Origem:
UInt32.cs
Origem:
UInt32.cs
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 da cultura sobre s.

Retornos

O resultado da análise s.

Implementações

Aplica-se a

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Origem:
UInt32.cs
Origem:
UInt32.cs
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 da cultura sobre utf8Text.

Retornos

O resultado da análise utf8Text.

Implementações

Aplica-se a

Parse(String)

Origem:
UInt32.cs
Origem:
UInt32.cs
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 equivalente inteiro sem sinal de 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

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 s parâmetro é null.

O s parâmetro não é do 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]

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

Elemento Descrição
Ws Espaço em branco opcional.
assinar Um sinal opcional. Caracteres de sinal válidos são determinados pelas propriedades e NumberFormatInfo.NegativeSign pela NumberFormatInfo.PositiveSign cultura atual. No entanto, o símbolo de sinal negativo só pode ser usado com zero; caso contrário, o método gerará um OverflowException.
Dígitos Uma sequência de dígitos variando de 0 a 9. Todos os zeros à esquerda são ignorados.

Nota

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

O s parâmetro é analisado usando as informações de formatação em um System.Globalization.NumberFormatInfo objeto inicializado para a cultura atual do sistema. 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

Parse(String, NumberStyles)

Origem:
UInt32.cs
Origem:
UInt32.cs
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 seu 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 o estilo especificado pelo style parâmetro.

style
NumberStyles

Uma combinação bit a bit dos 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 NumberStyles valor.

-ou-

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

s não está em um formato compatível com style.

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

-ou-

s inclui dígitos não zero e fracionários.

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 do 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 desabilitar o espaço em branco ou um símbolo de sinal.s

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

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

Elementos em colchetes ([ e ]) são opcionais. Se style incluir NumberStyles.AllowHexSpecifier, o s parâmetro poderá 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 style sinalizador e pode aparecer no final de NumberStyles.AllowLeadingWhite se s incluir o styleNumberStyles.AllowTrailingWhite sinalizador.
$ Um símbolo de moeda específico à cultura. Sua posição na cadeia de caracteres é definida pelas propriedades e NumberFormatInfo.CurrencyNegativePattern pela NumberFormatInfo.CurrencyPositivePattern cultura atual. O símbolo de moeda da cultura atual poderá aparecer s se style incluir o NumberStyles.AllowCurrencySymbol sinalizador.
assinar Um sinal opcional. O sinal pode aparecer no início de s se incluir o style sinalizador e pode aparecer no final de NumberStyles.AllowLeadingSign se s incluir o styleNumberStyles.AllowTrailingSign sinalizador. Parênteses podem ser usados s para indicar um valor negativo se style incluir o NumberStyles.AllowParentheses sinalizador. No entanto, o símbolo de sinal negativo só pode ser usado com zero; caso contrário, o método gerará 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 de grupo específico à cultura. O separador de grupo da cultura atual poderá aparecer s se style incluir o NumberStyles.AllowThousands sinalizador.
. Um símbolo de ponto decimal específico da cultura. O símbolo de ponto decimal da cultura atual poderá aparecer s se style incluir o NumberStyles.AllowDecimalPoint sinalizador. 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 na notação exponencial (científica). O s parâmetro pode representar um número na notação exponencial se style incluir o NumberStyles.AllowExponent sinalizador.
hexdigits Uma sequência de dígitos hexadecimal de 0 a f ou 0 a F.

Nota

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

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

Valor NumberStyles Elementos permitidos s além de dígitos
None Somente o elemento de dígitos .
AllowDecimalPoint O ponto decimal (.) e os elementos de 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 sign no final de s.
AllowParentheses O elemento sign na forma de parênteses que inclui o valor numérico.
AllowThousands O elemento separador de grupo (,).
AllowCurrencySymbol O elemento currency ($).
Currency Todos os elementos. No entanto, s não é possível 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, assinar no início e so símbolo de ponto decimal (.). O s parâmetro também pode usar notação exponencial.
Number Os wselementos separador signde grupo (,) e ponto decimal (.).
Any Todos os elementos. No entanto, s não é possível 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, so valor de NumberStyles.AllowHexSpecifier estilo significa que os caracteres s numéricos individuais sempre são interpretados como caracteres hexadecimal. Os caracteres hexadecimal 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 style parâmetro são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A NumberStyles enumeração inclui um estilo de número composto, NumberStyles.HexNumberque inclui sinalizadores de espaço em branco.)

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

Nota

Se s for a representação de cadeia de caracteres de um número hexadecimal, ela não poderá ser precedida por qualquer decoração (como 0x ou &h) que a diferencie como um número hexadecimal. Isso faz com que a conversão falhe.

O s parâmetro é analisado usando as informações de formatação em um NumberFormatInfo objeto inicializado para a cultura atual do sistema. 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