Int32.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 com sinal de 32 bits.
Sobrecargas
| Name | Description |
|---|---|
| Parse(String) |
Converte a representação da cadeia de um número para o seu equivalente inteiro com sinal de 32 bits. |
| Parse(ReadOnlySpan<Byte>, IFormatProvider) |
Analisa um intervalo de caracteres UTF-8 num valor. |
| Parse(ReadOnlySpan<Char>, IFormatProvider) |
Divide um intervalo de caracteres num valor. |
| Parse(String, NumberStyles) |
Converte a representação da cadeia de um número num estilo especificado para o seu equivalente inteiro com sinal de 32 bits. |
| Parse(String, IFormatProvider) |
Converte a representação da cadeia de um número num formato específico de cultura para o seu equivalente inteiro com sinal de 32 bits. |
| Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider) |
Analisa um intervalo de caracteres UTF-8 num valor. |
| Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) |
Converte a representação span de um número num estilo especificado e formato específico de cultura para o seu equivalente inteiro com sinal de 32 bits. |
| 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 com sinal de 32 bits. |
Parse(String)
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
Converte a representação da cadeia de um número para o seu equivalente inteiro com sinal de 32 bits.
public:
static int Parse(System::String ^ s);
public static int Parse(string s);
static member Parse : string -> int
Public Shared Function Parse (s As String) As Integer
Parâmetros
- s
- String
Uma cadeia contendo um número a converter.
Devoluções
Um inteiro com sinal de 32 bits equivalente ao número contido em s.
Exceções
s é null.
s não está no formato correto.
s representa um número inferior a Int32.MinValue ou superior a Int32.MaxValue.
Exemplos
O exemplo seguinte demonstra como converter um valor de cadeia num valor inteiro assinado de 32 bits usando o Int32.Parse(String) método. O valor inteiro resultante é então apresentado à consola.
using System;
public class Example
{
public static void Main()
{
string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127",
"0xFA1B", "163042", "-10", "007", "2147483647",
"2147483648", "16e07", "134985.0", "-12034",
"-2147483648", "-2147483649" };
foreach (string value in values)
{
try {
int number = Int32.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 --> -10
// 007 --> 7
// 2147483647 --> 2147483647
// 2147483648: Overflow
// 16e07: Bad Format
// 134985.0: Bad Format
// -12034 --> -12034
// -2147483648 --> -2147483648
// -2147483649: Overflow
open System
let values =
[ "+13230"; "-0"; "1,390,146"; "$190,235,421,127"
"0xFA1B"; "163042"; "-10"; "007"; "2147483647"
"2147483648"; "16e07"; "134985.0"; "-12034"
"-2147483648"; "-2147483649" ]
for value in values do
try
let number = Int32.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 --> -10
// 007 --> 7
// 2147483647 --> 2147483647
// 2147483648: Overflow
// 16e07: Bad Format
// 134985.0: Bad Format
// -12034 --> -12034
// -2147483648 --> -2147483648
// -2147483649: Overflow
Module Example
Public Sub Main()
Dim values() As String = { "+13230", "-0", "1,390,146", "$190,235,421,127",
"0xFA1B", "163042", "-10", "007", "2147483647",
"2147483648", "16e07", "134985.0", "-12034",
"-2147483648", "-2147483649" }
For Each value As String In values
Try
Dim number As Integer = Int32.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
End Sub
End Module
' 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 --> -10
' 007 --> 7
' 2147483647 --> 2147483647
' 2147483648: Overflow
' 16e07: Bad Format
' 134985.0: Bad Format
' -12034 --> -12034
' -2147483648 --> -2147483648
' -2147483649: Overflow
Observações
O s parâmetro contém um número da forma:
[ws][signo] 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. |
| sign | Um sinal opcional. |
| dígitos | Uma sequência de dígitos que varia de 0 a 9. |
O s parâmetro é interpretado usando o NumberStyles.Integer estilo. Para além dos dígitos decimais, apenas espaços iniciais e finais juntamente com um sinal inicial são permitidos. Para definir explicitamente os elementos de estilo que podem estar presentes em s, use o Int32.Parse(String, NumberStyles) ou o Int32.Parse(String, NumberStyles, IFormatProvider) método.
O s parâmetro é analisado usando a informação de formatação num NumberFormatInfo objeto inicializado para a cultura do sistema atual. Para obter mais informações, veja CurrentInfo. Para analisar uma cadeia usando a informação de formatação de outra cultura, use o Int32.Parse(String, NumberStyles, IFormatProvider) método.
Ver também
Aplica-se a
Parse(ReadOnlySpan<Byte>, IFormatProvider)
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
Analisa um intervalo de caracteres UTF-8 num valor.
public:
static int Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<int>::Parse;
public static int Parse(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> int
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As Integer
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(ReadOnlySpan<Char>, IFormatProvider)
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
Divide um intervalo de caracteres num valor.
public:
static int Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<int>::Parse;
public static int Parse(ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> int
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As Integer
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(String, NumberStyles)
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
Converte a representação da cadeia de um número num estilo especificado para o seu equivalente inteiro com sinal de 32 bits.
public:
static int Parse(System::String ^ s, System::Globalization::NumberStyles style);
public static int Parse(string s, System.Globalization.NumberStyles style);
static member Parse : string * System.Globalization.NumberStyles -> int
Public Shared Function Parse (s As String, style As NumberStyles) As Integer
Parâmetros
- s
- String
Uma cadeia contendo um número a converter.
- style
- NumberStyles
Uma combinação bit a bit dos valores de enumeração que indica os elementos de estilo que podem estar presentes em s. Um valor típico a especificar é Integer.
Devoluções
Um inteiro com sinal de 32 bits equivalente ao número especificado em s.
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 Int32.MinValue ou superior a Int32.MaxValue.
-ou-
s inclui dígitos fracionados e não nulos.
Exemplos
O exemplo seguinte utiliza o Int32.Parse(String, NumberStyles) método para analisar as representações de cadeias de vários Int32 valores. A cultura atual para o exemplo é en-US.
using System;
using System.Globalization;
public class ParseInt32
{
public static void Main()
{
Convert("104.0", NumberStyles.AllowDecimalPoint);
Convert("104.9", NumberStyles.AllowDecimalPoint);
Convert(" $17,198,064.42", NumberStyles.AllowCurrencySymbol |
NumberStyles.Number);
Convert("103E06", NumberStyles.AllowExponent);
Convert("-1,345,791", NumberStyles.AllowThousands);
Convert("(1,345,791)", NumberStyles.AllowThousands |
NumberStyles.AllowParentheses);
}
private static void Convert(string value, NumberStyles style)
{
try
{
int number = Int32.Parse(value, style);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", value);
}
catch (OverflowException)
{
Console.WriteLine("'{0}' is out of range of the Int32 type.", value);
}
}
}
// The example displays the following output to the console:
// Converted '104.0' to 104.
// '104.9' is out of range of the Int32 type.
// ' $17,198,064.42' is out of range of the Int32 type.
// Converted '103E06' to 103000000.
// Unable to convert '-1,345,791'.
// Converted '(1,345,791)' to -1345791.
open System
open System.Globalization
let convert value (style: NumberStyles) =
try
let number = Int32.Parse(value, style)
printfn $"Converted '{value}' to {number}."
with
| :? FormatException ->
printfn $"Unable to convert '{value}'."
| :? OverflowException ->
printfn $"'{value}' is out of range of the Int32 type."
convert "104.0" NumberStyles.AllowDecimalPoint
convert "104.9" NumberStyles.AllowDecimalPoint
convert " $17,198,064.42" (NumberStyles.AllowCurrencySymbol ||| NumberStyles.Number)
convert "103E06" NumberStyles.AllowExponent
convert "-1,345,791" NumberStyles.AllowThousands
convert "(1,345,791)" (NumberStyles.AllowThousands ||| NumberStyles.AllowParentheses)
// The example displays the following output to the console:
// Converted '104.0' to 104.
// '104.9' is out of range of the Int32 type.
// ' $17,198,064.42' is out of range of the Int32 type.
// Converted '103E06' to 103000000.
// Unable to convert '-1,345,791'.
// Converted '(1,345,791)' to -1345791.
Imports System.Globalization
Module ParseInt32
Public Sub Main()
Convert("104.0", NumberStyles.AllowDecimalPoint)
Convert("104.9", NumberStyles.AllowDecimalPoint)
Convert(" $17,198,064.42", NumberStyles.AllowCurrencySymbol Or _
NumberStyles.Number)
Convert("103E06", NumberStyles.AllowExponent)
Convert("-1,345,791", NumberStyles.AllowThousands)
Convert("(1,345,791)", NumberStyles.AllowThousands Or _
NumberStyles.AllowParentheses)
End Sub
Private Sub Convert(value As String, style As NumberStyles)
Try
Dim number As Integer = Int32.Parse(value, style)
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to convert '{0}'.", value)
Catch e As OverflowException
Console.WriteLine("'{0}' is out of range of the Int32 type.", value)
End Try
End Sub
End Module
' The example displays the following output to the console:
' Converted '104.0' to 104.
' '104.9' is out of range of the Int32 type.
' ' $17,198,064.42' is out of range of the Int32 type.
' Converted '103E06' to 103000000.
' Unable to convert '-1,345,791'.
' Converted '(1,345,791)' to -1345791.
Observações
O style parâmetro define os elementos de estilo (como espaço em branco, símbolo de sinal positivo ou negativo, ou símbolo do separador milhar) 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][$][sinal][dígitos,]dígitos[.fractional_digits][e[signo]exponential_digits][ws]
Ou, se style incluir AllowHexSpecifier:
[ws]hexdigits[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. 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 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 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 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 milhares específico de cultura. O separador dos milhares da cultura atual pode aparecer se sstyle 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, um OverflowException é lançado. |
| e | O carácter 'e' ou 'E', que indica que o valor é representado em notação exponencial. 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) faz sempre uma análise bem-sucedida se estiver no intervalo do Int32 tipo. A maioria dos membros restantes NumberStyles controla elementos que podem estar, mas não são obrigados a estar, presentes na cadeia de entrada. A tabela seguinte indica como os membros individuais NumberStyles afetam os elementos que podem estar presentes em s.
| Valor de NumberStyles | Elementos permitidos em s além dos dígitos |
|---|---|
| None | Apenas o elemento dígitos . |
| AllowDecimalPoint | Os elementos da vírgula decimal ( . ) e dos dígitos fracionários . |
| AllowExponent | O s parâmetro também pode usar notação exponencial. |
| 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 dos milhares ( , ). |
| AllowCurrencySymbol | O $ elemento. |
| Currency | Todos. O s parâmetro 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 elementosws, sign, milhares, separadores ( , ), e ponto decimal ( . ). |
| Any | Todos os estilos, exceto s , não podem representar um número hexadecimal. |
Se a NumberStyles.AllowHexSpecifier bandeira for usada, s deve ser um valor hexadecimal sem prefixo. Por exemplo, "C9AF3" analisa com sucesso, mas "0xC9AF3" não. Os únicos outros flags que podem ser combinados com o s parâmetro it 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.)
O s parâmetro é analisado usando 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 Int32.Parse(String, NumberStyles, IFormatProvider) sobrecarga.
Ver também
Aplica-se a
Parse(String, IFormatProvider)
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
Converte a representação da cadeia de um número num formato específico de cultura para o seu equivalente inteiro com sinal de 32 bits.
public:
static int Parse(System::String ^ s, IFormatProvider ^ provider);
public:
static int Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<int>::Parse;
public static int Parse(string s, IFormatProvider provider);
public static int Parse(string s, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> int
Public Shared Function Parse (s As String, provider As IFormatProvider) As Integer
Parâmetros
- s
- String
Uma cadeia contendo um 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 com sinal de 32 bits equivalente ao número especificado em s.
Implementações
Exceções
s é null.
s não tem o formato correto.
s representa um número inferior a Int32.MinValue ou superior a Int32.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 Int32 valor.
protected void OkToInteger_Click(object sender, EventArgs e)
{
string locale;
int 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 = Int32.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 OkToInteger_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OkToInteger.Click
Dim locale As String
Dim culture As CultureInfo
Dim number As Integer
' 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 = Int32.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
Esta sobrecarga do Parse(String, IFormatProvider) método é normalmente usada para converter texto que pode ser formatado de várias formas num Int32 valor. Por exemplo, pode ser usado para converter o texto introduzido por um utilizador numa caixa de texto HTML para um valor numérico.
O s parâmetro contém um número da forma:
[ws][signo] 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. |
| dígitos | Uma sequência de dígitos que varia de 0 a 9. |
O s parâmetro é interpretado usando o NumberStyles.Integer estilo. Para além dos dígitos decimais, apenas espaços iniciais e finais juntamente com um sinal inicial são permitidos. Para definir explicitamente os elementos de estilo que podem estar presentes em s, use o Int32.Parse(String, NumberStyles, IFormatProvider) método.
O provider parâmetro é uma IFormatProvider implementação, como um NumberFormatInfo objeto ou CultureInfo . O provider parâmetro fornece informação específica da cultura sobre o formato de s. Se provider for null, o NumberFormatInfo objeto para a cultura atual é usado.
Ver também
Aplica-se a
Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
Analisa um intervalo de caracteres UTF-8 num valor.
public static int Parse(ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> int
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Integer
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(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
Converte a representação span de um número num estilo especificado e formato específico de cultura para o seu equivalente inteiro com sinal de 32 bits.
public static int Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
public static int Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> int
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Integer
Parâmetros
- s
- ReadOnlySpan<Char>
Um espaço que contém os caracteres que representam o número a converter.
- 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 específica da cultura sobre o formato de s.
Devoluções
Um inteiro com sinal de 32 bits equivalente ao número especificado em s.
Implementações
Aplica-se a
Parse(String, NumberStyles, IFormatProvider)
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
- Origem:
- Int32.cs
Converte a representação em cadeia de um número num estilo especificado e formato específico de cultura para o seu equivalente inteiro com sinal de 32 bits.
public:
static int Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
static int Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<int>::Parse;
public static int Parse(string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static int Parse(string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> int
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As Integer
Parâmetros
- s
- String
Uma cadeia contendo um número a converter.
- 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 específica da cultura sobre o formato de s.
Devoluções
Um inteiro com sinal de 32 bits equivalente ao número especificado em s.
Implementações
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 Int32.MinValue ou superior a Int32.MaxValue.
-ou-
s inclui dígitos fracionados e não nulos.
Exemplos
O exemplo seguinte utiliza uma variedade de parâmetros e styleprovider para analisar as representações das cadeias de Int32 valores. Também ilustra algumas das diferentes formas como a mesma cadeia pode ser interpretada dependendo da cultura cuja informação de formatação é usada para a operação de análise sintática.
using System;
using System.Globalization;
public class ParseInt32
{
public static void Main()
{
Convert("12,000", NumberStyles.Float | NumberStyles.AllowThousands,
new CultureInfo("en-GB"));
Convert("12,000", NumberStyles.Float | NumberStyles.AllowThousands,
new CultureInfo("fr-FR"));
Convert("12,000", NumberStyles.Float, new CultureInfo("en-US"));
Convert("12 425,00", NumberStyles.Float | NumberStyles.AllowThousands,
new CultureInfo("sv-SE"));
Convert("12,425.00", NumberStyles.Float | NumberStyles.AllowThousands,
NumberFormatInfo.InvariantInfo);
Convert("631,900", NumberStyles.Integer | NumberStyles.AllowDecimalPoint,
new CultureInfo("fr-FR"));
Convert("631,900", NumberStyles.Integer | NumberStyles.AllowDecimalPoint,
new CultureInfo("en-US"));
Convert("631,900", NumberStyles.Integer | NumberStyles.AllowThousands,
new CultureInfo("en-US"));
}
private static void Convert(string value, NumberStyles style,
IFormatProvider provider)
{
try
{
int number = Int32.Parse(value, style, provider);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", value);
}
catch (OverflowException)
{
Console.WriteLine("'{0}' is out of range of the Int32 type.", value);
}
}
}
// This example displays the following output to the console:
// Converted '12,000' to 12000.
// Converted '12,000' to 12.
// Unable to convert '12,000'.
// Converted '12 425,00' to 12425.
// Converted '12,425.00' to 12425.
// '631,900' is out of range of the Int32 type.
// Unable to convert '631,900'.
// Converted '631,900' to 631900.
open System
open System.Globalization
let convert (value: string) (style: NumberStyles) (provider: IFormatProvider) =
try
let number = Int32.Parse(value, style, provider)
printfn $"Converted '{value}' to {number}."
with
| :? FormatException ->
printfn $"Unable to convert '{value}'."
| :? OverflowException ->
printfn $"'{value}' is out of range of the Int32 type."
convert "12,000" (NumberStyles.Float ||| NumberStyles.AllowThousands) (CultureInfo "en-GB")
convert "12,000" (NumberStyles.Float ||| NumberStyles.AllowThousands) (CultureInfo "fr-FR")
convert "12,000" NumberStyles.Float (CultureInfo "en-US")
convert "12 425,00" (NumberStyles.Float ||| NumberStyles.AllowThousands) (CultureInfo "sv-SE")
convert "12,425.00" (NumberStyles.Float ||| NumberStyles.AllowThousands) NumberFormatInfo.InvariantInfo
convert "631,900" (NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint) (CultureInfo "fr-FR")
convert "631,900" (NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint) (CultureInfo "en-US")
convert "631,900" (NumberStyles.Integer ||| NumberStyles.AllowThousands) (CultureInfo "en-US")
// This example displays the following output to the console:
// Converted '12,000' to 12000.
// Converted '12,000' to 12.
// Unable to convert '12,000'.
// Converted '12 425,00' to 12425.
// Converted '12,425.00' to 12425.
// '631,900' is out of range of the Int32 type.
// Unable to convert '631,900'.
// Converted '631,900' to 631900.
Imports System.Globalization
Module ParseInt32
Public Sub Main()
Convert("12,000", NumberStyles.Float Or NumberStyles.AllowThousands, _
New CultureInfo("en-GB"))
Convert("12,000", NumberStyles.Float Or NumberStyles.AllowThousands, _
New CultureInfo("fr-FR"))
Convert("12,000", NumberStyles.Float, New CultureInfo("en-US"))
Convert("12 425,00", NumberStyles.Float Or NumberStyles.AllowThousands, _
New CultureInfo("sv-SE"))
Convert("12,425.00", NumberStyles.Float Or NumberStyles.AllowThousands, _
NumberFormatInfo.InvariantInfo)
Convert("631,900", NumberStyles.Integer Or NumberStyles.AllowDecimalPoint, _
New CultureInfo("fr-FR"))
Convert("631,900", NumberStyles.Integer Or NumberStyles.AllowDecimalPoint, _
New CultureInfo("en-US"))
Convert("631,900", NumberStyles.Integer Or NumberStyles.AllowThousands, _
New CultureInfo("en-US"))
End Sub
Private Sub Convert(value As String, style As NumberStyles, _
provider As IFormatProvider)
Try
Dim number As Integer = Int32.Parse(value, style, provider)
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to convert '{0}'.", value)
Catch e As OverflowException
Console.WriteLine("'{0}' is out of range of the Int32 type.", value)
End Try
End Sub
End Module
' This example displays the following output to the console:
' Converted '12,000' to 12000.
' Converted '12,000' to 12.
' Unable to convert '12,000'.
' Converted '12 425,00' to 12425.
' Converted '12,425.00' to 12425.
' '631,900' is out of range of the Int32 type.
' Unable to convert '631,900'.
' Converted '631,900' to 631900.
Observações
O style parâmetro define os elementos de estilo (como espaços em branco ou o sinal positivo) 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][$][sinal][dígitos,]dígitos[.fractional_digist][e[signo]exponential_digits][ws]
Ou, se style incluir AllowHexSpecifier:
[ws]hexdigits[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. 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 NumberFormatInfo.CurrencyPositivePattern propriedade do NumberFormatInfo objeto 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 sinal pode aparecer no início de s se inclui a style bandeira ou no final de NumberStyles.AllowLeadingSign se s inclui a style bandeira.NumberStyles.AllowTrailingSign Parênteses podem ser usados s para indicar um valor negativo se style incluir a NumberStyles.AllowParentheses bandeira. |
|
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 milhares específico de cultura. Os milhares de separadores da cultura especificados por provider podem aparecer em s se style incluir a NumberStyles.AllowThousands bandeira. |
| . | Um símbolo de ponto decimal específico para cada cultura. O símbolo da vírgula decimal da cultura especificado por provider 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, um OverflowException é lançado. |
| e | O carácter 'e' ou 'E', que indica que o valor é representado em notação exponencial. 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) analisa sempre com sucesso se estiver no intervalo do Int32 tipo. A maioria dos membros restantes NumberStyles controla elementos que podem estar, mas não são obrigados a estar, nesta cadeia de entrada. A tabela seguinte indica como os membros individuais NumberStyles afetam os elementos que podem estar presentes em s.
| Valores de NumberStyles não compostos | Elementos permitidos em s além dos dígitos |
|---|---|
| NumberStyles.None | Apenas dígitos decimais. |
| NumberStyles.AllowDecimalPoint | Os elementos da vírgula decimal ( . ) e dos dígitos fracionários . No entanto, os dígitos fracionários devem consistir apenas em um ou mais dígitos 0 ou é lançado OverflowException . |
| NumberStyles.AllowExponent | O s parâmetro também pode usar notação exponencial. Se s representa um número em notação exponencial, deve representar um inteiro dentro do intervalo do Int32 tipo de dado sem um componente fracionário não nulo. |
| NumberStyles.AllowLeadingWhite | O elemento ws no início de s. |
| NumberStyles.AllowTrailingWhite | O elemento ws no final de s. |
| NumberStyles.AllowLeadingSign | Um sinal positivo pode aparecer antes dos dígitos. |
| NumberStyles.AllowTrailingSign | Um sinal positivo pode aparecer após os dígitos. |
| NumberStyles.AllowParentheses | O elemento do signo na forma de parênteses que envolvem o valor numérico. |
| NumberStyles.AllowThousands | O elemento separador dos milhares ( , ). |
| NumberStyles.AllowCurrencySymbol | O $ elemento. |
Se a NumberStyles.AllowHexSpecifier bandeira for usada, s deve ser um valor hexadecimal sem prefixo. Por exemplo, "C9AF3" analisa com sucesso, mas "0xC9AF3" não. As únicas outras bandeiras que podem estar presentes em style e NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhite. (A NumberStyles enumeração tem um estilo numérico composto, NumberStyles.HexNumber, que inclui ambas as bandeiras de espaço em branco.)
O provider parâmetro é uma IFormatProvider implementação, como um NumberFormatInfo objeto ou CultureInfo . O provider parâmetro fornece informação específica da cultura utilizada na análise sintática. Se provider for null, o NumberFormatInfo objeto para a cultura atual é usado.