UInt32.Parse Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Converte a representação da cadeia de um número para o seu equivalente inteiro sem sinal de 32 bits.
Sobrecargas
| Name | Description |
|---|---|
| Parse(String, NumberStyles, IFormatProvider) |
Converte a representação em cadeia de um número num estilo especificado e formato específico de cultura para o seu equivalente inteiro sem sinal de 32 bits. |
| Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) |
Converte a representação em expansão de um número num estilo especificado e formato específico de cultura para o seu equivalente inteiro sem sinal de 32 bits. |
| Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider) |
Analisa um intervalo de caracteres UTF-8 num valor. |
| Parse(String, IFormatProvider) |
Converte a representação da cadeia de um número num formato específico de cultura para o seu equivalente inteiro sem sinal de 32 bits. |
| Parse(ReadOnlySpan<Char>, IFormatProvider) |
Divide um intervalo de caracteres num valor. |
| Parse(ReadOnlySpan<Byte>, IFormatProvider) |
Analisa um intervalo de caracteres UTF-8 num valor. |
| Parse(String) |
Converte a representação da cadeia de um número para o seu equivalente inteiro sem sinal de 32 bits. |
| Parse(String, NumberStyles) |
Converte a representação da cadeia de um número num estilo especificado para o seu equivalente inteiro sem sinal de 32 bits. |
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 em cadeia de um número num estilo especificado e formato específico de cultura para o seu equivalente inteiro sem sinal de 32 bits.
public:
static System::UInt32 Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
static System::UInt32 Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<System::UInt32>::Parse;
[System.CLSCompliant(false)]
public static uint Parse(string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static uint Parse(string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static uint Parse(string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> uint32
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> uint32
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As UInteger
Parâmetros
- s
- String
Uma sequência que representa o número a converter. A cadeia é 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 especificar é Integer.
- provider
- IFormatProvider
Um objeto que fornece informação de formatação específica de cultura sobre s.
Devoluções
Um inteiro sem sinal de 32 bits equivalente ao número especificado em s.
Implementações
- Atributos
Exceções
s é null.
style não é um NumberStyles valor.
-ou-
style não é uma combinação de AllowHexSpecifier valores e HexNumber .
s não está num formato compatível com style.
s representa um número inferior a UInt32.MinValue ou superior a UInt32.MaxValue.
-ou-
s inclui dígitos fracionados e não nulos.
Exemplos
O exemplo seguinte utiliza o Parse(String, NumberStyles, IFormatProvider) método para converter várias representações de cadeias 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.
Observações
O style parâmetro define os elementos de estilo (como espaços 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 sintética tenha sucesso. Deve ser uma combinação de indicadores de bits da NumberStyles enumeração.
Dependendo do valor de style, o s parâmetro pode incluir os seguintes elementos:
[ws][$][signo] dígitos[.fractional_digits][E[signo]exponential_digits][ws]
Os elementos entre parênteses retos ([ e ]) são opcionais. Se style inclui NumberStyles.AllowHexSpecifier, o s parâmetro pode 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 style inclui a NumberStyles.AllowLeadingWhite bandeira, e pode aparecer no final de s se style inclui a NumberStyles.AllowTrailingWhite bandeira. |
| $ | Um símbolo monetário específico de cada cultura. A sua posição na cadeia é definida pela CurrencyPositivePattern propriedade do NumberFormatInfo objeto que é devolvida pelo GetFormat método do provider parâmetro. O símbolo da moeda pode aparecer se sstyle incluir a NumberStyles.AllowCurrencySymbol bandeira. |
| assinar | Um sinal opcional. (O método lança um OverflowException ses, inclui um sinal negativo e representa um número não nulo.) O sinal pode aparecer no início de s se inclui a style bandeira, e pode aparecer no final de NumberStyles.AllowLeadingSign se s inclui a styleNumberStyles.AllowTrailingSign bandeira. Parênteses podem ser usados s para indicar um valor negativo se style incluir a NumberStyles.AllowParentheses bandeira. |
| dígitos | Uma sequência de dígitos de 0 a 9. |
| . | Um símbolo de ponto decimal específico para cada cultura. O símbolo de ponto decimal da cultura atual pode aparecer em s se style incluir a NumberStyles.AllowDecimalPoint bandeira. |
| fractional_digits | Uma ou mais ocorrências do dígito 0-9 se style incluir a NumberStyles.AllowExponent bandeira, ou uma ou mais ocorrências do dígito 0 se não incluir. Os dígitos fracionários só podem aparecer se sstyle incluir a NumberStyles.AllowDecimalPoint bandeira. |
| E | O carácter "e" ou "E", que indica que o valor é representado em notação exponencial (científica). O s parâmetro pode representar um número em notação exponencial se style incluir a NumberStyles.AllowExponent bandeira. |
| exponential_digits | Uma sequência de dígitos de 0 a 9. O s parâmetro pode representar um número em notação exponencial se style incluir a NumberStyles.AllowExponent bandeira. |
| Hexdigits | Uma sequência de dígitos hexadecimais de 0 a f, ou de 0 a F. |
Note
Quaisquer caracteres NUL terminantes (U+0000) em s são ignorados pela operação de análise, independentemente do valor do style argumento.
Uma cadeia apenas com dígitos decimais (que corresponde ao NumberStyles.None estilo) faz sempre análise com sucesso. A maioria dos membros restantes NumberStyles controla elementos que podem estar presentes, mas que não são obrigados a estar presentes, nesta cadeia de entrada. A tabela seguinte 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 dos dígitos |
|---|---|
| NumberStyles.None | Apenas dígitos decimais. |
| NumberStyles.AllowDecimalPoint | A vírgula decimal (.) e fractional_digits elementos. No entanto, se o estilo não incluir a NumberStyles.AllowExponent bandeira, fractional_digits deve consistir apenas de um ou mais dígitos 0; caso contrário, um OverflowException é lançado. |
| NumberStyles.AllowExponent | O carácter "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 depois dos dígitos. |
| NumberStyles.AllowParentheses | Parênteses entre dígitos antes e depois para indicar um valor negativo. |
| NumberStyles.AllowThousands | O elemento separador de grupo (,). |
| NumberStyles.AllowCurrencySymbol | O elemento da moeda ($). |
Se a NumberStyles.AllowHexSpecifier bandeira for usada, s deve ser um valor hexadecimal. As únicas outras bandeiras que podem ser combinadas com ela são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A NumberStyles enumeração inclui um estilo numérico composto, NumberStyles.HexNumber, que inclui ambas as bandeiras de espaço em branco.)
Note
Se o s parâmetro for a representação em cadeia de um número hexadecimal, não pode ser precedido por nenhuma decoração (como 0x ou &h) que o diferencie de um número hexadecimal. Isto faz com que a operação de análise sintética lance uma exceção.
O provider parâmetro é uma IFormatProvider implementação cujo GetFormat método devolve um NumberFormatInfo objeto que fornece informação específica de cultura sobre o formato de s. Existem três formas de usar o provider parâmetro para fornecer informação de formatação personalizada à operação de análise sintática:
Podes passar o objeto real NumberFormatInfo que fornece a informação de formatação. (A sua implementação de GetFormat simplesmente devolve-se a si própria.)
Pode passar um CultureInfo objeto que especifique a cultura cuja formatação deve ser usada. A sua NumberFormat propriedade fornece informação de formatação.
Pode passar uma implementação personalizada IFormatProvider . O seu GetFormat método deve instanciar e devolver o NumberFormatInfo objeto que fornece a informação de formatação.
Se provider for null, o NumberFormatInfo objeto para a cultura atual é usado.
Ver 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 em expansão de um número num estilo especificado e formato específico de cultura para o seu equivalente inteiro sem sinal de 32 bits.
public static uint Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
[System.CLSCompliant(false)]
public static uint Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
[System.CLSCompliant(false)]
public static uint Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> uint32
[<System.CLSCompliant(false)>]
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> uint32
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As UInteger
Parâmetros
- s
- ReadOnlySpan<Char>
Um espaço que contém os caracteres que representam o número a converter. O vão é 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 especificar é Integer.
- provider
- IFormatProvider
Um objeto que fornece informação de formatação específica de cultura sobre s.
Devoluções
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 num 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>
A extensão de caracteres UTF-8 para analisar.
- style
- NumberStyles
Uma combinação bit a bit de estilos numéricos que pode estar presente em utf8Text.
- provider
- IFormatProvider
Um objeto que fornece informação de formatação específica da cultura sobre utf8Text.
Devoluções
O resultado da análise sintática 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 da cadeia de um número num formato específico de cultura para o seu equivalente inteiro sem sinal de 32 bits.
public:
static System::UInt32 Parse(System::String ^ s, IFormatProvider ^ provider);
public:
static System::UInt32 Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<System::UInt32>::Parse;
[System.CLSCompliant(false)]
public static uint Parse(string s, IFormatProvider provider);
public static uint Parse(string s, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static uint Parse(string s, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * IFormatProvider -> uint32
static member Parse : string * IFormatProvider -> uint32
Public Shared Function Parse (s As String, provider As IFormatProvider) As UInteger
Parâmetros
- s
- String
Uma cadeia que representa o número a converter.
- provider
- IFormatProvider
Um objeto que fornece informação de formatação específica de cultura sobre s.
Devoluções
Um inteiro sem sinal de 32 bits equivalente ao número especificado em s.
Implementações
- Atributos
Exceções
s é null.
s não está no estilo correto.
s representa um número inferior a UInt32.MinValue ou superior a UInt32.MaxValue.
Exemplos
O exemplo seguinte é o handler de eventos com clique de botão de um formulário Web. Utiliza o array devolvido pela HttpRequest.UserLanguages propriedade para determinar a localização do utilizador. De seguida, instância é um CultureInfo objeto que corresponde a esse local. O NumberFormatInfo objeto que pertence a esse CultureInfo objeto é então passado ao Parse(String, IFormatProvider) método para converter a entrada do utilizador num 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
Observações
O s parâmetro contém um número da forma:
[ws][sinal]dígitos[ws]
Itens entre parênteses ([ 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 que varia de 0 a 9. |
O parâmetro s é interpretado usando o NumberStyles.Integer estilo. Para além dos dígitos decimais do valor inteiro sem sinal, apenas os espaços iniciais e finais juntamente com um sinal à esquerda são permitidos. (Se o sinal negativo estiver presente, s deve representar um valor zero, ou o método lança um OverflowException.) Para definir explicitamente os elementos de estilo juntamente com a informação de formatação específica da cultura que pode estar presente em s, utilize o Parse(String, NumberStyles, IFormatProvider) método.
O provider parâmetro é uma IFormatProvider implementação cujo GetFormat método devolve um NumberFormatInfo objeto que fornece informação específica de cultura sobre o formato de s. Existem três formas de usar o provider parâmetro para fornecer informação de formatação personalizada à operação de análise sintática:
Podes passar o objeto real NumberFormatInfo que fornece a informação de formatação. (A sua implementação de GetFormat simplesmente devolve-se a si própria.)
Pode passar um CultureInfo objeto que especifique a cultura cuja formatação deve ser usada. A sua NumberFormat propriedade fornece informação de formatação.
Pode passar uma implementação personalizada IFormatProvider . O seu GetFormat método deve instanciar e devolver o NumberFormatInfo objeto que fornece a informação de formatação.
Se provider for null, o NumberFormatInfo para a cultura atual é usado.
Ver também
Aplica-se a
Parse(ReadOnlySpan<Char>, IFormatProvider)
- Origem:
- UInt32.cs
- Origem:
- UInt32.cs
- Origem:
- UInt32.cs
- Origem:
- UInt32.cs
- Origem:
- UInt32.cs
Divide um intervalo de caracteres num 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 número de personagens a analisar.
- provider
- IFormatProvider
Um objeto que fornece informação de formatação específica da cultura sobre s.
Devoluções
O resultado da análise sintática 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 num 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>
A extensão de caracteres UTF-8 para analisar.
- provider
- IFormatProvider
Um objeto que fornece informação de formatação específica da cultura sobre utf8Text.
Devoluções
O resultado da análise sintática 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 da cadeia de um número para o 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 sequência que representa o número a converter.
Devoluções
Um inteiro não assinado 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 inferior a UInt32.MinValue ou superior a UInt32.MaxValue.
Exemplos
O exemplo seguinte utiliza o Parse(String) método para analisar um array de valores de cadeia.
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
Observações
O s parâmetro deve ser a representação em cadeia de um número na seguinte forma.
[ws][sinal]dígitos[ws]
Os elementos entre parênteses retos ([ 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 signo válidos são determinados pelas NumberFormatInfo.NegativeSign propriedades e NumberFormatInfo.PositiveSign da cultura atual. No entanto, o símbolo do signo negativo só pode ser usado com zero; caso contrário, o método lança um OverflowException. |
| dígitos | Uma sequência de dígitos que varia de 0 a 9. Quaisquer zeros à esquerda são ignorados. |
Note
A cadeia especificada pelo s parâmetro é interpretada usando o NumberStyles.Integer estilo. Não pode conter separadores de grupo ou separadores decimais, nem pode ter uma parte decimal.
O s parâmetro é analisado utilizando a informação de formatação num System.Globalization.NumberFormatInfo objeto que é inicializado para a cultura do sistema atual. Para obter mais informações, veja NumberFormatInfo.CurrentInfo. Para analisar uma cadeia usando a informação de formatação de uma cultura específica, use o Parse(String, IFormatProvider) método.
Ver 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 da cadeia de um número num estilo especificado para o seu equivalente inteiro sem sinal de 32 bits.
public:
static System::UInt32 Parse(System::String ^ s, System::Globalization::NumberStyles style);
[System.CLSCompliant(false)]
public static uint Parse(string s, System.Globalization.NumberStyles style);
public static uint Parse(string s, System.Globalization.NumberStyles style);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles -> uint32
static member Parse : string * System.Globalization.NumberStyles -> uint32
Public Shared Function Parse (s As String, style As NumberStyles) As UInteger
Parâmetros
- s
- String
Uma sequência que representa o número a converter. A cadeia é 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 especificar é Integer.
Devoluções
Um inteiro sem sinal de 32 bits equivalente ao número especificado em s.
- Atributos
Exceções
s é null.
style não é um NumberStyles valor.
-ou-
style não é uma combinação de AllowHexSpecifier valores e HexNumber .
s não está num formato compatível com style.
s representa um número inferior a UInt32.MinValue ou superior a UInt32.MaxValue.
-ou-
s inclui dígitos fracionados e não nulos.
Exemplos
O exemplo seguinte tenta analisar cada elemento num array de NumberStyles cadeias usando vários 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
Observações
O style parâmetro define os elementos de estilo (como espaço em branco, símbolo de sinal positivo ou negativo, símbolo de separador de grupo ou símbolo de ponto decimal) que são permitidos no s parâmetro para que a operação de análise sintática tenha sucesso.
style deve ser uma combinação de flags de bits da NumberStyles enumeração. O style parâmetro torna este método sobrecarregado útil quando s contém a representação em cadeia de um valor hexadecimal, quando o sistema numérico (decimal ou hexadecimal) representado por s é conhecido apenas em tempo de execução, ou quando se pretende impedir espaço em branco ou um símbolo de sinal em s.
Dependendo do valor de style, o s parâmetro pode incluir os seguintes elementos:
[ws][$][signo][dígitos,]dígitos[.fractional_digits][E[sign]exponential_digits][ws]
Os elementos entre parênteses retos ([ e ]) são opcionais. Se style inclui NumberStyles.AllowHexSpecifier, o s parâmetro 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 if style inclui a NumberStyles.AllowLeadingWhite bandeira, e pode aparecer no final de s if style inclui a NumberStyles.AllowTrailingWhite bandeira. |
| $ | Um símbolo monetário específico de cada cultura. A sua posição na corda é definida pelas NumberFormatInfo.CurrencyNegativePattern propriedades e NumberFormatInfo.CurrencyPositivePattern da cultura atual. O símbolo monetário da cultura atual pode aparecer se sstyle incluir a NumberStyles.AllowCurrencySymbol bandeira. |
| assinar | Um sinal opcional. O sinal pode aparecer no início de s se incluir a style bandeira, e pode aparecer no final de NumberStyles.AllowLeadingSign se s incluir a styleNumberStyles.AllowTrailingSign bandeira. Parênteses podem ser usados s para indicar um valor negativo se style incluir a NumberStyles.AllowParentheses bandeira. No entanto, o símbolo do signo negativo só pode ser usado com zero; caso 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, apenas o dígito 0 é válido. |
| , | Um símbolo separador de grupo específico de cada cultura. O separador de grupo da cultura atual pode aparecer em s se style incluir a NumberStyles.AllowThousands bandeira. |
| . | Um símbolo de ponto decimal específico para cada cultura. O símbolo de ponto decimal da cultura atual pode aparecer em s se style incluir a NumberStyles.AllowDecimalPoint bandeira. Apenas o dígito 0 pode aparecer como um dígito fracionário para que a operação de análise sintética tenha sucesso; Se fractional_digits incluir qualquer outro dígito, a FormatException é lançado. |
| E | O carácter "e" ou "E", que indica que o valor é representado em notação exponencial (científica). O s parâmetro pode representar um número em notação exponencial se style incluir a NumberStyles.AllowExponent bandeira. |
| Hexdigits | Uma sequência de dígitos hexadecimais de 0 a f, ou de 0 a F. |
Note
Quaisquer caracteres NUL terminantes (U+0000) em s são ignorados pela operação de análise, independentemente do valor do style argumento.
Uma cadeia apenas com dígitos (que corresponde ao NumberStyles.None estilo) analisa sempre com sucesso se estiver no intervalo do UInt32 tipo. A maioria dos membros restantes NumberStyles controla elementos que podem estar presentes, mas não são obrigados a estar, na cadeia de entrada. A tabela seguinte indica como os membros individuais NumberStyles afetam os elementos que podem estar presentes em s.
NumberStyles valor |
Elementos permitidos s além dos dígitos |
|---|---|
| None | Apenas o elemento dígitos . |
| AllowDecimalPoint | Os elementos de ponto decimal (.) e de dígitos fracionários . |
| AllowExponent | O carácter "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 signo no início de s. |
| AllowTrailingSign | O elemento signo no final de s. |
| AllowParentheses | O elemento do signo na forma de parênteses que envolvem o valor numérico. |
| AllowThousands | O elemento separador de grupo (,). |
| AllowCurrencySymbol | O elemento da 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 fim de s, sinal no início de s, e o símbolo da vírgula decimal (.). O s parâmetro 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 NumberStyles.AllowHexSpecifier valor de estilo significa que os caracteres numéricos individuais em s são sempre interpretados como caracteres hexadecimais. Caracteres hexadecimais válidos são 0-9, A-F e a-f. Um prefixo, como "0x", não é permitido. Os únicos outros flags que podem ser combinados com o style parâmetro são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A NumberStyles enumeração inclui um estilo numérico composto, NumberStyles.HexNumber, que inclui ambas as bandeiras de espaço em branco.)
Os únicos outros flags que podem ser combinados com o style parâmetro são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A NumberStyles enumeração inclui um estilo numérico composto, NumberStyles.HexNumber, que inclui ambas as bandeiras de espaço em branco.)
Note
Se s for a representação em cadeia de um número hexadecimal, não pode ser precedida por qualquer decoração (como 0x ou &h) que a diferencie como número hexadecimal. Isto faz com que a conversão falhe.
O s parâmetro é analisado utilizando a informação de formatação num NumberFormatInfo objeto que é inicializado para a cultura do sistema atual. Para especificar a cultura cuja informação de formatação é usada para a operação de análise sintática, chame-se a Parse(String, NumberStyles, IFormatProvider) sobrecarga.