Int16.Parse Método
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Converte a representação de cadeia de caracteres de um número no inteiro com sinal de 16 bits equivalente.
Sobrecargas
Parse(String, NumberStyles, IFormatProvider) |
Converte a representação de cadeia de caracteres de um número em um estilo e formato específico da cultura especificados em seu equivalente de inteiro com sinal de 16 bits. |
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) |
Converte a representação de intervalo de um número em um formato específico da cultura e um estilo especificados em seu equivalente de inteiro com sinal de 16 bits. |
Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider) |
Analisa um intervalo de caracteres UTF-8 em um valor. |
Parse(String, IFormatProvider) |
Converte a representação de cadeia de caracteres de um número em um formato específico à cultura especificado no inteiro com sinal de 16 bits equivalente. |
Parse(String) |
Converte a representação de cadeia de caracteres de um número no inteiro com sinal de 16 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, NumberStyles) |
Converte a representação de cadeia de caracteres de um número em um estilo especificado em um inteiro com sinal de 16 bits equivalente. |
Parse(String, NumberStyles, IFormatProvider)
Converte a representação de cadeia de caracteres de um número em um estilo e formato específico da cultura especificados em seu equivalente de inteiro com sinal de 16 bits.
public:
static short Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
static short Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<short>::Parse;
public static short Parse (string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static short Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> int16
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As Short
Parâmetros
- s
- String
Uma cadeia de caracteres que contém um número a ser convertido.
- style
- NumberStyles
Um combinação bit a bit de valores de enumeração que indica os elementos de estilo que podem estar presentes em s
. Um valor típico a ser especificado é Integer.
- provider
- IFormatProvider
Um IFormatProvider que fornece informações de formatação específica de cultura sobre s
.
Retornos
Um inteiro com sinal de 16 bits equivalente ao número especificado em s
.
Implementações
Exceções
s
é null
.
style
não é um valor NumberStyles.
- ou -
style
não é uma combinação de valores AllowHexSpecifier e HexNumber.
s
não está em um formato em conformidade com style
.
s
representa um número menor que Int16.MinValue ou maior que Int16.MaxValue.
- ou -
s
inclui dígitos fracionários diferentes de zero.
Exemplos
O exemplo a seguir usa uma variedade de style
parâmetros e provider
para analisar as representações de cadeia de caracteres de Int16 valores.
String^ value;
Int16 number;
NumberStyles style;
// Parse string using "." as the thousands separator
// and " " as the decimal separator.
value = "19 694,00";
style = NumberStyles::AllowDecimalPoint | NumberStyles::AllowThousands;
CultureInfo^ provider = gcnew CultureInfo("fr-FR");
number = Int16::Parse(value, style, provider);
Console::WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
// '19 694,00' converted to 19694.
try
{
number = Int16::Parse(value, style, CultureInfo::InvariantCulture);
Console::WriteLine("'{0}' converted to {1}.", value, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to parse '{0}'.", value);
}
// Displays:
// Unable to parse '19 694,00'.
// Parse string using "$" as the currency symbol for en_GB and
// en-US cultures.
value = "$6,032.00";
style = NumberStyles::Number | NumberStyles::AllowCurrencySymbol;
provider = gcnew CultureInfo("en-GB");
try
{
number = Int16::Parse(value, style, CultureInfo::InvariantCulture);
Console::WriteLine("'{0}' converted to {1}.", value, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to parse '{0}'.", value);
}
// Displays:
// Unable to parse '$6,032.00'.
provider = gcnew CultureInfo("en-US");
number = Int16::Parse(value, style, provider);
Console::WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
// '$6,032.00' converted to 6032.
string value;
short number;
NumberStyles style;
CultureInfo provider;
// Parse string using "." as the thousands separator
// and " " as the decimal separator.
value = "19 694,00";
style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
provider = new CultureInfo("fr-FR");
number = Int16.Parse(value, style, provider);
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
// '19 694,00' converted to 19694.
try
{
number = Int16.Parse(value, style, CultureInfo.InvariantCulture);
Console.WriteLine("'{0}' converted to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}'.", value);
}
// Displays:
// Unable to parse '19 694,00'.
// Parse string using "$" as the currency symbol for en_GB and
// en-US cultures.
value = "$6,032.00";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
provider = new CultureInfo("en-GB");
try
{
number = Int16.Parse(value, style, CultureInfo.InvariantCulture);
Console.WriteLine("'{0}' converted to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}'.", value);
}
// Displays:
// Unable to parse '$6,032.00'.
provider = new CultureInfo("en-US");
number = Int16.Parse(value, style, provider);
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
// '$6,032.00' converted to 6032.
// Parse string using "." as the thousands separator
// and " " as the decimal separator.
let value = "19 694,00"
let style = NumberStyles.AllowDecimalPoint ||| NumberStyles.AllowThousands
let provider = CultureInfo "fr-FR"
let number = Int16.Parse(value, style, provider)
printfn $"'{value}' converted to {number}."
// Displays:
// '19 694,00' converted to 19694.
try
let number = Int16.Parse(value, style, CultureInfo.InvariantCulture)
printfn $"'{value}' converted to {number}."
with :? FormatException ->
printfn $"Unable to parse '{value}'."
// Displays:
// Unable to parse '19 694,00'.
// Parse string using "$" as the currency symbol for en_GB and
// en-US cultures.
let value = "$6,032.00"
let style = NumberStyles.Number ||| NumberStyles.AllowCurrencySymbol
try
let number = Int16.Parse(value, style, CultureInfo.InvariantCulture)
printfn $"'{value}' converted to {number}."
with :? FormatException ->
printfn $"Unable to parse '{value}'."
// Displays:
// Unable to parse '$6,032.00'.
let provider = CultureInfo "en-US"
let number = Int16.Parse(value, style, provider)
printfn $"'{value}' converted to {number}."
// Displays:
// '$6,032.00' converted to 6032.
Dim value As String
Dim number As Short
Dim style As NumberStyles
Dim provider As CultureInfo
' Parse string using "." as the thousands separator
' and " " as the decimal separator.
value = "19 694,00"
style = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowThousands
provider = New CultureInfo("fr-FR")
number = Int16.Parse(value, style, provider)
Console.WriteLine("'{0}' converted to {1}.", value, number)
' Displays:
' '19 694,00' converted to 19694.
Try
number = Int16.Parse(value, style, CultureInfo.InvariantCulture)
Console.WriteLine("'{0}' converted to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}'.", value)
End Try
' Displays:
' Unable to parse '19 694,00'.
' Parse string using "$" as the currency symbol for en_GB and
' en-US cultures.
value = "$6,032.00"
style = NumberStyles.Number Or NumberStyles.AllowCurrencySymbol
provider = New CultureInfo("en-GB")
Try
number = Int16.Parse(value, style, CultureInfo.InvariantCulture)
Console.WriteLine("'{0}' converted to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}'.", value)
End Try
' Displays:
' Unable to parse '$6,032.00'.
provider = New CultureInfo("en-US")
number = Int16.Parse(value, style, provider)
Console.WriteLine("'{0}' converted to {1}.", value, number)
' Displays:
' '$6,032.00' converted to 6032.
Comentários
O parâmetro style
define os elementos de estilo (como espaço em branco ou o sinal positivo) que são permitidos no parâmetro s
para que a operação de análise seja bem-sucedida. Ele deve ser uma combinação de sinalizadores de bits da enumeração NumberStyles. Dependendo do valor de style
, o parâmetro s
pode incluir os seguintes elementos:
[ws][$][sign][digits,]digits[.fractional_digits][e[sign]digits][ws]
Ou, caso style
inclua AllowHexSpecifier:
[ws]hexdigits[ws]
Os elementos entre colchetes ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.
Elemento | Descrição |
---|---|
ws | Espaço em branco opcional. O espaço em branco pode ser exibido no início de s caso style inclua o sinalizador NumberStyles.AllowLeadingWhite ou no final de s caso style inclua o sinalizador NumberStyles.AllowTrailingWhite. |
$ | Um símbolo de moeda específico de cultura. Sua posição na cadeia de caracteres é definida pela NumberFormatInfo.CurrencyPositivePattern propriedade e NumberFormatInfo.CurrencyNegativePattern da cultura atual. O símbolo de moeda da cultura atual pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowCurrencySymbol. |
sign | Um sinal opcional. O sinal pode ser exibido no início de s caso style inclua o sinalizador NumberStyles.AllowLeadingSign e ele pode ser exibido no final de s caso style inclua o sinalizador NumberStyles.AllowTrailingSign. Os parênteses podem ser usados em s para indicar um valor negativo caso style inclua o sinalizador NumberStyles.AllowParentheses. |
dígitos | Uma sequência de dígitos de 0 a 9. |
, | Um símbolo de separador de milhares específico da cultura. O símbolo do separador do grupo da cultura atual pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowThousands. |
. | Um símbolo de vírgula decimal específico de cultura. O símbolo da vírgula decimal da cultura atual pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowDecimalPoint. |
Fractional_digits | Uma sequência do dígito 0. Os dígitos fracionários podem ser exibidos em s caso style inclua o sinalizador NumberStyles.AllowDecimalPoint. Se qualquer dígito diferente de 0 aparecer em fractional_digits, o método gerará um OverflowException. |
e | O caractere 'e' ou 'E', que indica que s pode ser representado na notação exponencial. O parâmetro s pode representar um número em notação exponencial caso style inclua o sinalizador NumberStyles.AllowExponent. No entanto, o s parâmetro deve representar um número no intervalo do Int16 tipo de dados e não pode ter um componente fracionário diferente de zero. |
hexdigits | Uma sequência de dígitos hexadecimais de 0 a f ou de 0 a F. |
Observação
Todos os caracteres NUL de terminação (U+0000) em s
são ignorados pela operação de análise, independentemente do valor do style
argumento.
Uma cadeia de caracteres com apenas dígitos (que corresponde ao NumberStyles.None estilo) sempre analisa com êxito. A maioria dos elementos de controle dos membros NumberStyles restantes que podem estar, mas que não precisam estar presentes nessa cadeia de caracteres de entrada. A tabela a seguir indica como os membros NumberStyles individuais afetam os elementos que podem estar presentes em s
.
Valores NumberStyles não compostos | Elementos permitidos em s além de dígitos |
---|---|
NumberStyles.None | Somente dígitos decimais. |
NumberStyles.AllowDecimalPoint | Os elementos . e fractional_digits . No entanto, fractional_digits deve consistir em apenas um ou mais 0 dígitos ou um OverflowException é lançado. |
NumberStyles.AllowExponent | O parâmetro s também pode usar notação exponencial. |
NumberStyles.AllowLeadingWhite | O elemento ws no início de s . |
NumberStyles.AllowTrailingWhite | O elemento ws no final de s . |
NumberStyles.AllowLeadingSign | Um sinal pode aparecer antes dos dígitos. |
NumberStyles.AllowTrailingSign | Um sinal pode aparecer após dígitos. |
NumberStyles.AllowParentheses | O elemento sinal na forma de parênteses que incluem o valor numérico. |
NumberStyles.AllowThousands | O elemento , . |
NumberStyles.AllowCurrencySymbol | O $ elemento . |
Se o NumberStyles.AllowHexSpecifier sinalizador for usado, s
deverá ser a representação de cadeia de caracteres de um valor hexadecimal sem um prefixo. Por exemplo, "9AF3" analisa com êxito, mas "0x9AF3" não. Os únicos outros sinalizadores que podem estar presentes em style
são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A enumeração de NumberStyles tem um estilo de número composto, NumberStyles.HexNumber, que inclui ambos os sinalizadores de espaço em branco.)
O provider
parâmetro é uma implementação IFormatProvider cujo GetFormat método obtém um NumberFormatInfo objeto . O objeto NumberFormatInfo fornece informações específicas da cultura sobre o formato de s
. Caso provider
seja null
, o objeto NumberFormatInfo da cultura atual é usado.
Confira também
Aplica-se a
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)
Converte a representação de intervalo de um número em um formato específico da cultura e um estilo especificados em seu equivalente de inteiro com sinal de 16 bits.
public static short Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
public static short Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> int16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Short
Parâmetros
- s
- ReadOnlySpan<Char>
Um intervalo que contém os caracteres que representam o número a ser convertido.
- style
- NumberStyles
Um combinação bit a bit de valores de enumeração que indica os elementos de estilo que podem estar presentes em s
. Um valor típico a ser especificado é Integer.
- provider
- IFormatProvider
Um IFormatProvider que fornece informações de formatação específica de cultura sobre s
.
Retornos
Um inteiro com sinal de 16 bits equivalente ao número especificado em s
.
Implementações
Aplica-se a
Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)
Analisa um intervalo de caracteres UTF-8 em um valor.
public static short Parse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> int16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Short
Parâmetros
- utf8Text
- ReadOnlySpan<Byte>
O intervalo de caracteres UTF-8 a serem analisados.
- style
- NumberStyles
Uma combinação bit a bit de estilos numéricos que podem estar presentes em utf8Text
.
- provider
- IFormatProvider
Um objeto que fornece informações de formatação específicas à cultura sobre utf8Text
.
Retornos
O resultado da análise utf8Text
.
Implementações
Aplica-se a
Parse(String, IFormatProvider)
Converte a representação de cadeia de caracteres de um número em um formato específico à cultura especificado no inteiro com sinal de 16 bits equivalente.
public:
static short Parse(System::String ^ s, IFormatProvider ^ provider);
public:
static short Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<short>::Parse;
public static short Parse (string s, IFormatProvider provider);
public static short Parse (string s, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> int16
Public Shared Function Parse (s As String, provider As IFormatProvider) As Short
Parâmetros
- s
- String
Uma cadeia de caracteres que contém um número a ser convertido.
- provider
- IFormatProvider
Um IFormatProvider que fornece informações de formatação específica de cultura sobre s
.
Retornos
Um inteiro com sinal de 16 bits equivalente ao número especificado em s
.
Implementações
Exceções
s
é null
.
s
não está no formato correto.
s
representa um número menor que Int16.MinValue ou maior que Int16.MaxValue.
Exemplos
O exemplo a seguir analisa representações de cadeia de caracteres de Int16 valores com o Int16.Parse(String, IFormatProvider) método .
String^ stringToConvert;
Int16 number;
stringToConvert = " 214 ";
try
{
number = Int16::Parse(stringToConvert, CultureInfo::InvariantCulture);
Console::WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException ^e)
{
Console::WriteLine("'{0'} is out of range of the Int16 data type.",
stringToConvert);
}
stringToConvert = " + 214";
try
{
number = Int16::Parse(stringToConvert, CultureInfo::InvariantCulture);
Console::WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException ^e)
{
Console::WriteLine("'{0'} is out of range of the Int16 data type.",
stringToConvert);
}
stringToConvert = " +214 ";
try
{
number = Int16::Parse(stringToConvert, CultureInfo::InvariantCulture);
Console::WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException ^e)
{
Console::WriteLine("'{0'} is out of range of the Int16 data type.",
stringToConvert);
}
// The example displays the following output to the console:
// Converted ' 214 ' to 214.
// Unable to parse ' + 214'.
// Converted ' +214 ' to 214.
string stringToConvert;
short number;
stringToConvert = " 214 ";
try
{
number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture);
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException)
{
Console.WriteLine("'{0'} is out of range of the Int16 data type.",
stringToConvert);
}
stringToConvert = " + 214";
try
{
number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture);
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException)
{
Console.WriteLine("'{0'} is out of range of the Int16 data type.",
stringToConvert);
}
stringToConvert = " +214 ";
try
{
number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture);
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException)
{
Console.WriteLine("'{0'} is out of range of the Int16 data type.",
stringToConvert);
}
// The example displays the following output to the console:
// Converted ' 214 ' to 214.
// Unable to parse ' + 214'.
// Converted ' +214 ' to 214.
let stringToConvert = " 214 "
try
let number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
printfn $"Converted '{stringToConvert}' to {number}."
with
| :? FormatException ->
printfn $"Unable to parse '{stringToConvert}'."
| :? OverflowException ->
printfn $"'{stringToConvert}' is out of range of the Int16 data type."
let stringToConvert = " + 214"
try
let number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
printfn $"Converted '{stringToConvert}' to {number}."
with
| :? FormatException ->
printfn $"Unable to parse '{stringToConvert}'."
| :? OverflowException ->
printfn $"'{stringToConvert}' is out of range of the Int16 data type."
let stringToConvert = " +214 "
try
let number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
printfn $"Converted '{stringToConvert}' to {number}."
with
| :? FormatException ->
printfn $"Unable to parse '{stringToConvert}'."
| :? OverflowException ->
printfn $"'{stringToConvert}' is out of range of the Int16 data type."
// The example displays the following output to the console:
// Converted ' 214 ' to 214.
// Unable to parse ' + 214'.
// Converted ' +214 ' to 214.
Dim stringToConvert As String
Dim number As Short
stringToConvert = " 214 "
Try
number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}'.", stringToConvert)
Catch e As OverflowException
Console.WriteLine("'{0'} is out of range of the Int16 data type.", _
stringToConvert)
End Try
stringToConvert = " + 214"
Try
number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}'.", stringToConvert)
Catch e As OverflowException
Console.WriteLine("'{0'} is out of range of the Int16 data type.", _
stringToConvert)
End Try
stringToConvert = " +214 "
Try
number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}'.", stringToConvert)
Catch e As OverflowException
Console.WriteLine("'{0'} is out of range of the Int16 data type.", _
stringToConvert)
End Try
' The example displays the following output to the console:
' Converted ' 214 ' to 214.
' Unable to parse ' + 214'.
' Converted ' +214 ' to 214.
Comentários
O parâmetro s
contém um número da forma:
[ws][sign]digits[ws]
Os elementos entre colchetes ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.
Elemento | Descrição |
---|---|
ws | Um espaço em branco opcional. |
sinal | Um sinal opcional. |
dígitos | Uma sequência de dígitos que varia de 0 a 9. |
O parâmetro s
é interpretado usando-se o estilo NumberStyles.Integer. Além de dígitos decimais, somente espaços à esquerda e à direita, juntamente com um sinal à esquerda, são permitidos em s
. Para definir explicitamente os elementos de estilo junto com as informações de formatação específicas da cultura que podem estar presentes no s
, use o Int16.Parse(String, NumberStyles, IFormatProvider) método .
O provider
parâmetro é uma implementação IFormatProvider que obtém um NumberFormatInfo objeto . O NumberFormatInfo fornece informações específicas da cultura sobre o formato de s
. Caso provider
seja null
, NumberFormatInfo da cultura atual é usado.
Confira também
Aplica-se a
Parse(String)
Converte a representação de cadeia de caracteres de um número no inteiro com sinal de 16 bits equivalente.
public:
static short Parse(System::String ^ s);
public static short Parse (string s);
static member Parse : string -> int16
Public Shared Function Parse (s As String) As Short
Parâmetros
- s
- String
Uma cadeia de caracteres que contém um número a ser convertido.
Retornos
Um inteiro com sinal de 16 bits equivalente ao número contido em s
.
Exceções
s
é null
.
s
não está no formato correto.
s
representa um número menor que Int16.MinValue ou maior que Int16.MaxValue.
Exemplos
O exemplo a seguir demonstra como converter um valor de cadeia de caracteres em um valor inteiro com sinal de 16 bits usando o Int16.Parse(String) método . O valor inteiro resultante é exibido no console.
String^ value;
Int16 number;
value = " 12603 ";
try
{
number = Int16::Parse(value);
Console::WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
value);
}
value = " 16,054";
try
{
number = Int16::Parse(value);
Console::WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
value);
}
value = " -17264";
try
{
number = Int16::Parse(value);
Console::WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
value);
}
// The example displays the following output to the console:
// Converted ' 12603 ' to 12603.
// Unable to convert ' 16,054' to a 16-bit signed integer.
// Converted ' -17264' to -17264.
string value;
short number;
value = " 12603 ";
try
{
number = Int16.Parse(value);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
value);
}
value = " 16,054";
try
{
number = Int16.Parse(value);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
value);
}
value = " -17264";
try
{
number = Int16.Parse(value);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
value);
}
// The example displays the following output to the console:
// Converted ' 12603 ' to 12603.
// Unable to convert ' 16,054' to a 16-bit signed integer.
// Converted ' -17264' to -17264.
let value = " 12603 "
try
let number = Int16.Parse value
printfn $"Converted '{value}' to {number}."
with :? FormatException ->
printfn $"Unable to convert '{value}' to a 16-bit signed integer."
let value = " 16,054"
try
let number = Int16.Parse value
printfn $"Converted '{value}' to {number}."
with :? FormatException ->
printfn "Unable to convert '{value}' to a 16-bit signed integer."
let value = " -17264"
try
let number = Int16.Parse value
printfn $"Converted '{value}' to {number}."
with :? FormatException ->
printfn "Unable to convert '{value}' to a 16-bit signed integer."
// The example displays the following output to the console:
// Converted ' 12603 ' to 12603.
// Unable to convert ' 16,054' to a 16-bit signed integer.
// Converted ' -17264' to -17264.
Dim value As String
Dim number As Short
value = " 12603 "
Try
number = Short.Parse(value)
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.", _
value)
End Try
value = " 16,054"
Try
number = Short.Parse(value)
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.", _
value)
End Try
value = " -17264"
Try
number = Short.Parse(value)
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.", _
value)
End Try
' The example displays the following output to the console:
' Converted ' 12603 ' to 12603.
' Unable to convert ' 16,054' to a 16-bit signed integer.
' Converted ' -17264' to -17264.
Comentários
O parâmetro s
contém um número da forma:
[ws][sign]digits[ws]
Os elementos entre colchetes ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.
Elemento | Descrição |
---|---|
ws | Espaço em branco opcional. |
sign | Um sinal opcional. |
dígitos | Uma sequência de dígitos que varia de 0 a 9. |
O parâmetro s
é interpretado usando-se o estilo NumberStyles.Integer. Além dos dígitos decimais do valor inteiro, somente espaços à esquerda e à direita, juntamente com um sinal à esquerda, são permitidos. Para definir explicitamente os elementos de estilo que podem estar presentes no s
, use o Int16.Parse(String, NumberStyles) método ou Parse .
O parâmetro s
é analisado usando-se as informações de formatação em um objeto NumberFormatInfo que é inicializado para a cultura do sistema atual. Para obter mais informações, consulte CurrentInfo. Para analisar uma cadeia de caracteres usando as informações de formatação de alguma outra cultura, use o Int16.Parse(String, IFormatProvider) método ou Int16.Parse(String, NumberStyles, IFormatProvider) .
Confira também
Aplica-se a
Parse(ReadOnlySpan<Char>, IFormatProvider)
Analisa um intervalo de caracteres em um valor.
public:
static short Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<short>::Parse;
public static short Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> int16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As Short
Parâmetros
- s
- ReadOnlySpan<Char>
O intervalo de caracteres a serem analisados.
- provider
- IFormatProvider
Um objeto que fornece informações de formatação específicas à cultura sobre s
.
Retornos
O resultado da análise s
.
Implementações
Aplica-se a
Parse(ReadOnlySpan<Byte>, IFormatProvider)
Analisa um intervalo de caracteres UTF-8 em um valor.
public:
static short Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<short>::Parse;
public static short Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> int16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As Short
Parâmetros
- utf8Text
- ReadOnlySpan<Byte>
O intervalo de caracteres UTF-8 a serem analisados.
- provider
- IFormatProvider
Um objeto que fornece informações de formatação específicas à cultura sobre utf8Text
.
Retornos
O resultado da análise utf8Text
.
Implementações
Aplica-se a
Parse(String, NumberStyles)
Converte a representação de cadeia de caracteres de um número em um estilo especificado em um inteiro com sinal de 16 bits equivalente.
public:
static short Parse(System::String ^ s, System::Globalization::NumberStyles style);
public static short Parse (string s, System.Globalization.NumberStyles style);
static member Parse : string * System.Globalization.NumberStyles -> int16
Public Shared Function Parse (s As String, style As NumberStyles) As Short
Parâmetros
- s
- String
Uma cadeia de caracteres que contém um número a ser convertido.
- style
- NumberStyles
Um 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 ser especificado é Integer.
Retornos
Um inteiro com sinal de 16 bits equivalente ao número especificado em s
.
Exceções
s
é null
.
style
não é um valor NumberStyles.
- ou -
style
não é uma combinação de valores AllowHexSpecifier e HexNumber.
s
não está em um formato em conformidade com style
.
s
representa um número menor que Int16.MinValue ou maior que Int16.MaxValue.
- ou -
s
inclui dígitos fracionários diferentes de zero.
Exemplos
O exemplo a seguir usa o Int16.Parse(String, NumberStyles) método para analisar as representações de cadeia de caracteres de Int16 valores usando a cultura en-US.
using namespace System;
using namespace System::Globalization;
ref class ParseSample
{
public:
static void Main()
{
String^ value;
NumberStyles style;
// Parse a number with a thousands separator (throws an exception).
value = "14,644";
style = NumberStyles::None;
ParseSample::ParseToInt16(value, style);
style = NumberStyles::AllowThousands;
ParseToInt16(value, style);
// Parse a number with a thousands separator and decimal point.
value = "14,644.00";
style = NumberStyles::AllowThousands | NumberStyles::Integer |
NumberStyles::AllowDecimalPoint;
ParseToInt16(value, style);
// Parse a number with a fractional component (throws an exception).
value = "14,644.001";
ParseToInt16(value, style);
// Parse a number in exponential notation.
value = "145E02";
style = style | NumberStyles::AllowExponent;
ParseToInt16(value, style);
// Parse a number in exponential notation with a positive sign.
value = "145E+02";
ParseToInt16(value, style);
// Parse a number in exponential notation with a negative sign
// (throws an exception).
value = "145E-02";
ParseToInt16(value, style);
}
private:
static void ParseToInt16(String^ value, NumberStyles style)
{
try
{
Int16 number = Int16::Parse(value, style);
Console::WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to parse '{0}' with style {1}.", value,
style);
}
catch (OverflowException ^e)
{
Console::WriteLine("'{0}' is out of range of the Int16 type.", value);
}
}
};
int main()
{
ParseSample::Main();
Console::ReadLine();
return 0;
}
// The example displays the following output:
// Unable to parse '14,644' with style None.
// Converted '14,644' to 14644.
// Converted '14,644.00' to 14644.
// '14,644.001' is out of range of the Int16 type.
// Converted '145E02' to 14500.
// Converted '145E+02' to 14500.
// '145E-02' is out of range of the Int16 type.
using System;
using System.Globalization;
public class ParseSample
{
public static void Main()
{
string value;
NumberStyles style;
// Parse a number with a thousands separator (throws an exception).
value = "14,644";
style = NumberStyles.None;
ParseToInt16(value, style);
style = NumberStyles.AllowThousands;
ParseToInt16(value, style);
// Parse a number with a thousands separator and decimal point.
value = "14,644.00";
style = NumberStyles.AllowThousands | NumberStyles.Integer |
NumberStyles.AllowDecimalPoint;
ParseToInt16(value, style);
// Parse a number with a fractional component (throws an exception).
value = "14,644.001";
ParseToInt16(value, style);
// Parse a number in exponential notation.
value = "145E02";
style = style | NumberStyles.AllowExponent;
ParseToInt16(value, style);
// Parse a number in exponential notation with a positive sign.
value = "145E+02";
ParseToInt16(value, style);
// Parse a number in exponential notation with a negative sign
// (throws an exception).
value = "145E-02";
ParseToInt16(value, style);
}
private static void ParseToInt16(string value, NumberStyles style)
{
try
{
short number = Int16.Parse(value, style);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}' with style {1}.", value,
style.ToString());
}
catch (OverflowException)
{
Console.WriteLine("'{0}' is out of range of the Int16 type.", value);
}
}
}
// The example displays the following output to the console:
// Unable to parse '14,644' with style None.
// Converted '14,644' to 14644.
// Converted '14,644.00' to 14644.
// '14,644.001' is out of range of the Int16 type.
// Converted '145E02' to 14500.
// Converted '145E+02' to 14500.
// '145E-02' is out of range of the Int16 type.
open System
open System.Globalization
let parseToInt16 (value: string) (style: NumberStyles) =
try
let number = Int16.Parse(value, style)
printfn $"Converted '{value}' to {number}."
with
| :? FormatException ->
printfn $"Unable to parse '{value}' with style {style}."
| :? OverflowException ->
printfn $"'{value}' is out of range of the Int16 type."
[<EntryPoint>]
let main _ =
// Parse a number with a thousands separator (throws an exception).
let value = "14,644"
let style = NumberStyles.None
parseToInt16 value style
let style = NumberStyles.AllowThousands
parseToInt16 value style
// Parse a number with a thousands separator and decimal point.
let value = "14,644.00"
let style = NumberStyles.AllowThousands ||| NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
parseToInt16 value style
// Parse a number with a fractional component (throws an exception).
let value = "14,644.001"
parseToInt16 value style
// Parse a number in exponential notation.
let value = "145E02"
let style = style ||| NumberStyles.AllowExponent
parseToInt16 value style
// Parse a number in exponential notation with a positive sign.
let value = "145E+02"
parseToInt16 value style
// Parse a number in exponential notation with a negative sign
// (throws an exception).
let value = "145E-02"
parseToInt16 value style
0
// The example displays the following output to the console:
// Unable to parse '14,644' with style None.
// Converted '14,644' to 14644.
// Converted '14,644.00' to 14644.
// '14,644.001' is out of range of the Int16 type.
// Converted '145E02' to 14500.
// Converted '145E+02' to 14500.
// '145E-02' is out of range of the Int16 type.
Imports System.Globalization
Module ParseSample
Public Sub Main()
Dim value As String
Dim style As NumberStyles
' Parse a number with a thousands separator (throws an exception).
value = "14,644"
style = NumberStyles.None
ParseToInt16(value, style)
style = NumberStyles.AllowThousands
ParseToInt16(value, style)
' Parse a number with a thousands separator and decimal point.
value = "14,644.00"
style = NumberStyles.AllowThousands Or NumberStyles.Integer Or _
NumberStyles.AllowDecimalPoint
ParseToInt16(value, style)
' Parse a number with a fractional component (throws an exception).
value = "14,644.001"
ParseToInt16(value, style)
' Parse a number in exponential notation.
value = "145E02"
style = style Or NumberStyles.AllowExponent
ParseToInt16(value, style)
' Parse a number in exponential notation with a positive sign.
value = "145E+02"
ParseToInt16(value, style)
' Parse a number in exponential notation with a negative sign
' (throws an exception).
value = "145E-02"
ParseToInt16(value, style)
End Sub
Private Sub ParseToInt16(value As String, style As NumberStyles)
Try
Dim number As Short = Int16.Parse(value, style)
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}' with style {1}.", value, _
style.ToString())
Catch e As OverflowException
Console.WriteLine("'{0}' is out of range of the Int16 type.", value)
End Try
End Sub
End Module
' The example displays the following output to the console:
' Unable to parse '14,644' with style None.
' Converted '14,644' to 14644.
' Converted '14,644.00' to 14644.
' '14,644.001' is out of range of the Int16 type.
' Converted '145E02' to 14500.
' Converted '145E+02' to 14500.
' '145E-02' is out of range of the Int16 type.
Comentários
O style
parâmetro define os elementos de estilo (como espaço em branco ou um símbolo de sinal) que são permitidos no s
parâmetro para que a operação de análise tenha êxito. Ele deve ser uma combinação de sinalizadores de bits da enumeração NumberStyles. Dependendo do valor de style
, o parâmetro s
pode incluir os seguintes elementos:
[ws][$][sign][digits,]digits[.fractional_digits][e[sign]digits][ws]
Ou, caso style
inclua AllowHexSpecifier:
[ws]hexdigits[ws]
Itens entre colchetes ([ 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 ser exibido no início de s caso style inclua o sinalizador NumberStyles.AllowLeadingWhite ou no final de s caso style inclua o sinalizador NumberStyles.AllowTrailingWhite. |
$ | Um símbolo de moeda específico de cultura. Sua posição na cadeia de caracteres é definida pela NumberFormatInfo.CurrencyPositivePattern propriedade e NumberFormatInfo.CurrencyNegativePattern da cultura atual. O símbolo de moeda da cultura atual pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowCurrencySymbol. |
sign | Um sinal opcional. O sinal pode ser exibido no início de s caso style inclua o sinalizador NumberStyles.AllowLeadingSign e ele pode ser exibido no final de s caso style inclua o sinalizador NumberStyles.AllowTrailingSign. Os parênteses podem ser usados em s para indicar um valor negativo caso style inclua o sinalizador NumberStyles.AllowParentheses. |
dígitos | Uma sequência de dígitos de 0 a 9. |
, | Um símbolo de separador de milhares específico da cultura. O símbolo do separador do grupo da cultura atual pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowThousands. |
. | Um símbolo de vírgula decimal específico de cultura. O símbolo da vírgula decimal da cultura atual pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowDecimalPoint. |
Fractional_digits | Uma sequência do dígito 0. Os dígitos fracionários podem ser exibidos em s caso style inclua o sinalizador NumberStyles.AllowDecimalPoint. Se qualquer dígito diferente de 0 aparecer em fractional_digits, o método gerará um OverflowException. |
e | O caractere 'e' ou 'E', que indica que s pode ser representado em notação exponencial. O parâmetro s pode representar um número em notação exponencial caso style inclua o sinalizador NumberStyles.AllowExponent. No entanto, o s parâmetro deve representar um número no intervalo do tipo de Int16 dados e não pode ter um componente fracionário diferente de zero. |
hexdigits | Uma sequência de dígitos hexadecimais de 0 a f ou de 0 a F. |
Observação
Todos os caracteres NUL de terminação (U+0000) no s
são ignorados pela operação de análise, independentemente do valor do style
argumento.
Uma cadeia de caracteres somente com dígitos (que corresponde ao NumberStyles.None estilo) sempre analisa com êxito. A maioria dos elementos de controle dos membros NumberStyles restantes que podem estar, mas que não precisam estar presentes nessa cadeia de caracteres de entrada. A tabela a seguir indica como os membros NumberStyles individuais afetam os elementos que podem estar presentes em s
.
Valores NumberStyles não compostos | Elementos permitidos em s além de dígitos |
---|---|
NumberStyles.None | Somente dígitos decimais. |
NumberStyles.AllowDecimalPoint | Os elementos . e fractional_digits . No entanto, fractional_digits deve consistir em apenas um ou mais 0 dígitos ou um OverflowException é gerado. |
NumberStyles.AllowExponent | O parâmetro s também pode usar notação exponencial. |
NumberStyles.AllowLeadingWhite | O elemento ws no início de s . |
NumberStyles.AllowTrailingWhite | O elemento ws no final de s . |
NumberStyles.AllowLeadingSign | Um sinal pode aparecer antes dos dígitos. |
NumberStyles.AllowTrailingSign | Um sinal pode aparecer após dígitos. |
NumberStyles.AllowParentheses | O elemento sinal na forma de parênteses que incluem o valor numérico. |
NumberStyles.AllowThousands | O elemento , . |
NumberStyles.AllowCurrencySymbol | O $ elemento . |
Se o NumberStyles.AllowHexSpecifier sinalizador for usado, s
deverá ser a representação de cadeia de caracteres de um valor hexadecimal sem um prefixo. Por exemplo, "9AF3" analisa com êxito, mas "0x9AF3" não. Os únicos outros sinalizadores que podem estar presentes em style
são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A enumeração de NumberStyles tem um estilo de número composto, NumberStyles.HexNumber, que inclui ambos os sinalizadores de espaço em branco.)
O parâmetro s
é analisado usando-se as informações de formatação em um objeto NumberFormatInfo que é inicializado para a cultura do sistema atual. Para obter mais informações, consulte NumberFormatInfo.CurrentInfo. Para analisar s
usando as informações de formatação de uma cultura específica, chame o Int16.Parse(String, NumberStyles, IFormatProvider) método .
Confira também
Aplica-se a
Comentários
Enviar e exibir comentários de