Int16.TryParse Método
Definição
Converte a representação de cadeia de caracteres de um número no inteiro com sinal de 16 bits equivalente.Converts the string representation of a number to its 16-bit signed integer equivalent. Um valor retornado indica se a conversão foi bem-sucedida ou falhou.A return value indicates whether the conversion succeeded or failed.
Sobrecargas
TryParse(String, Int16) |
Converte a representação de cadeia de caracteres de um número no inteiro com sinal de 16 bits equivalente.Converts the string representation of a number to its 16-bit signed integer equivalent. Um valor retornado indica se a conversão foi bem-sucedida ou falhou.A return value indicates whether the conversion succeeded or failed. |
TryParse(ReadOnlySpan<Char>, Int16) |
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.Converts the span representation of a number in a specified style and culture-specific format to its 16-bit signed integer equivalent. Um valor retornado indica se a conversão foi bem-sucedida ou falhou.A return value indicates whether the conversion succeeded or failed. |
TryParse(String, NumberStyles, IFormatProvider, Int16) |
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.Converts the string representation of a number in a specified style and culture-specific format to its 16-bit signed integer equivalent. Um valor retornado indica se a conversão foi bem-sucedida ou falhou.A return value indicates whether the conversion succeeded or failed. |
TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int16) |
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.Converts the span representation of a number in a specified style and culture-specific format to its 16-bit signed integer equivalent. Um valor retornado indica se a conversão foi bem-sucedida ou falhou.A return value indicates whether the conversion succeeded or failed. |
TryParse(String, Int16)
Converte a representação de cadeia de caracteres de um número no inteiro com sinal de 16 bits equivalente.Converts the string representation of a number to its 16-bit signed integer equivalent. Um valor retornado indica se a conversão foi bem-sucedida ou falhou.A return value indicates whether the conversion succeeded or failed.
public:
static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] short % result);
public static bool TryParse (string s, out short result);
public static bool TryParse (string? s, out short? result);
static member TryParse : string * int16 -> bool
Public Shared Function TryParse (s As String, ByRef result As Short) As Boolean
Parâmetros
- s
- String
Uma cadeia de caracteres que contém um número a ser convertido.A string containing a number to convert.
- result
- Int16
Quando esse método for retornado, conterá o equivalente do valor inteiro com sinal de 16 bits do número contido em s
, se a conversão tiver sido bem-sucedida, ou conterá zero, se a conversão tiver falhado.When this method returns, contains the 16-bit signed integer value equivalent to the number contained in s
, if the conversion succeeded, or zero if the conversion failed. A conversão falhará se o parâmetro s
for null
ou Empty, não estiver em um formato correto ou representar um número menor que MinValue ou maior que MaxValue.The conversion fails if the s
parameter is null
or Empty, is not of the correct format, or represents a number less than MinValue or greater than MaxValue. Este parâmetro é passado não inicializado; qualquer valor fornecido originalmente em result
será substituído.This parameter is passed uninitialized; any value originally supplied in result
will be overwritten.
Retornos
true
caso s
tenha sido convertido com êxito; do contrário, false
.true
if s
was converted successfully; otherwise, false
.
Exemplos
O exemplo a seguir chama o Int16.TryParse(String, Int16) método com um número de valores de cadeia de caracteres diferentes.The following example calls the Int16.TryParse(String, Int16) method with a number of different string values.
using System;
public class StringParsing
{
public static void Main()
{
TryToParse(null);
TryToParse("16051");
TryToParse("9432.0");
TryToParse("16,667");
TryToParse(" -322 ");
TryToParse("+4302");
TryToParse("(100);");
TryToParse("01FA");
}
private static void TryToParse(string value)
{
short number;
bool result = Int16.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
}
}
// The example displays the following output to the console:
// Attempted conversion of '' failed.
// Converted '16051' to 16051.
// Attempted conversion of '9432.0' failed.
// Attempted conversion of '16,667' failed.
// Converted ' -322 ' to -322.
// Converted '+4302' to 4302.
// Attempted conversion of '(100)' failed.
// Attempted conversion of '01FA' failed.
Module StringParsing
Public Sub Main()
TryToParse(Nothing)
TryToParse("16051")
TryToParse("9432.0")
TryToParse("16,667")
TryToParse(" -322 ")
TryToParse("+4302")
TryToParse("(100)")
TryToParse("01FA")
End Sub
Private Sub TryToParse(value As String)
Dim number As Int16
Dim result As Boolean = Int16.TryParse(value, number)
If result Then
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
If value Is Nothing Then value = ""
Console.WriteLine("Attempted conversion of '{0}' failed.", value)
End If
End Sub
End Module
' The example displays the following output to the console:
' Attempted conversion of '' failed.
' Converted '16051' to 16051.
' Attempted conversion of '9432.0' failed.
' Attempted conversion of '16,667' failed.
' Converted ' -322 ' to -322.
' Converted '+4302' to 4302.
' Attempted conversion of '(100)' failed.
' Attempted conversion of '01FA' failed.
Algumas das cadeias de caracteres que o TryParse(String, Int16) método não pode converter neste exemplo são:Some of the strings that the TryParse(String, Int16) method is unable to convert in this example are:
"9432,0"."9432.0". A conversão falha porque a cadeia de caracteres não pode conter um separador decimal; Ele deve conter apenas dígitos integrais.The conversion fails because the string cannot contain a decimal separator; it must contain integral digits only.
"16.667"."16,667". A conversão falha porque a cadeia de caracteres não pode conter separadores de grupo; Ele deve conter apenas dígitos integrais.The conversion fails because the string cannot contain group separators; it must contain integral digits only.
"(100)"."(100)". A conversão falha porque a cadeia de caracteres não pode conter um sinal negativo diferente daquele definido pelas NumberFormatInfo.NegativeSign Propriedades e culturas atuais NumberFormatInfo.NumberNegativePattern .The conversion fails because the string cannot contain a negative sign other than the one defined by the current culture's NumberFormatInfo.NegativeSign and NumberFormatInfo.NumberNegativePattern properties.
"01FA"."01FA". A conversão falha porque a cadeia de caracteres não pode conter dígitos hexadecimais; Ele deve conter apenas dígitos decimais.The conversion fails because the string cannot contain hexadecimal digits; it must contain decimal digits only.
Comentários
O Int16.TryParse(String, Int16) método difere do Int16.Parse(String) método retornando um valor booliano que indica se a operação de análise teve êxito em vez de retornar o valor analisado Int16 .The Int16.TryParse(String, Int16) method differs from the Int16.Parse(String) method by returning a Boolean value that indicates whether the parse operation succeeded instead of returning the parsed Int16 value. Ele elimina a necessidade de usar a identificação de exceções para testar um FormatException caso esse s
seja inválido e não possa ser analisado com êxito.It eliminates the need to use exception handling to test for a FormatException in the event that s
is invalid and cannot be successfully parsed.
O s
parâmetro deve ser a representação de cadeia de caracteres de um número no formato:The s
parameter should be the string representation of a number in the form:
[ws][sign]digits[ws][ws][sign]digits[ws]
Itens entre colchetes ([ e ]) são opcionais.Items in square brackets ([ and ]) are optional. A tabela a seguir descreve cada elemento.The following table describes each element.
ElementoElement | DescriçãoDescription |
---|---|
wsws | Espaço em branco opcional.Optional white space. |
signsign | Um sinal opcional.An optional sign. |
dígitosdigits | Uma sequência de dígitos que varia de 0 a 9.A sequence of digits ranging from 0 to 9. |
O parâmetro s
é interpretado usando-se o estilo NumberStyles.Integer.The s
parameter is interpreted using the NumberStyles.Integer style. Além dos dígitos decimais, são permitidos apenas espaços à esquerda e à direita, juntamente com um sinal à esquerda.In addition to the decimal digits, only leading and trailing spaces together with a leading sign are allowed. Para definir explicitamente os elementos de estilo junto com as informações de formatação específicas de cultura que podem estar presentes no s
, use o Int16.TryParse(String, NumberStyles, IFormatProvider, Int16) método.To explicitly define the style elements together with the culture-specific formatting information that can be present in s
, use the Int16.TryParse(String, NumberStyles, IFormatProvider, Int16) method.
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.The s
parameter is parsed using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. Para obter mais informações, consulte CurrentInfo.For more information, see CurrentInfo.
Essa sobrecarga do TryParse método interpreta todos os dígitos no s
parâmetro como dígitos decimais.This overload of the TryParse method interprets all digits in the s
parameter as decimal digits. Para analisar a representação de cadeia de caracteres de um número hexadecimal, chame a Int16.TryParse(String, NumberStyles, IFormatProvider, Int16) sobrecarga.To parse the string representation of a hexadecimal number, call the Int16.TryParse(String, NumberStyles, IFormatProvider, Int16) overload.
Confira também
- Parse(String)
- ToString()
- Análise de cadeias de caracteres numéricas no .NETParsing Numeric Strings in .NET
- Amostra: Utilitário de Formatação do WinForms do .NET Core (C#)Sample: .NET Core WinForms Formatting Utility (C#)
- Amostra: Utilitário de Formatação do WinForms do .NET Core (Visual Basic)Sample: .NET Core WinForms Formatting Utility (Visual Basic)
Aplica-se a
TryParse(ReadOnlySpan<Char>, Int16)
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.Converts the span representation of a number in a specified style and culture-specific format to its 16-bit signed integer equivalent. Um valor retornado indica se a conversão foi bem-sucedida ou falhou.A return value indicates whether the conversion succeeded or failed.
public:
static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] short % result);
public static bool TryParse (ReadOnlySpan<char> s, out short result);
static member TryParse : ReadOnlySpan<char> * int16 -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As Short) As Boolean
Parâmetros
- s
- ReadOnlySpan<Char>
Um intervalo que contém os caracteres que representam o número a ser convertido.A span containing the characters representing the number to convert.
- result
- Int16
Quando esse método for retornado, conterá o equivalente do valor inteiro com sinal de 16 bits do número contido em s
, se a conversão tiver sido bem-sucedida, ou conterá zero, se a conversão tiver falhado.When this method returns, contains the 16-bit signed integer value equivalent to the number contained in s
, if the conversion succeeded, or zero if the conversion failed. A conversão falhará se o parâmetro s
for null
ou Empty, não estiver em um formato em conformidade com style
ou representar um número menor que MinValue ou maior que MaxValue.The conversion fails if the s
parameter is null
or Empty, is not in a format compliant with style
, or represents a number less than MinValue or greater than MaxValue. Este parâmetro é passado não inicializado; qualquer valor fornecido originalmente em result
será substituído.This parameter is passed uninitialized; any value originally supplied in result
will be overwritten.
Retornos
true
caso s
tenha sido convertido com êxito; do contrário, false
.true
if s
was converted successfully; otherwise, false
.
Aplica-se a
TryParse(String, NumberStyles, IFormatProvider, Int16)
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.Converts the string representation of a number in a specified style and culture-specific format to its 16-bit signed integer equivalent. Um valor retornado indica se a conversão foi bem-sucedida ou falhou.A return value indicates whether the conversion succeeded or failed.
public:
static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] short % result);
public static bool TryParse (string s, System.Globalization.NumberStyles style, IFormatProvider provider, out short result);
public static bool TryParse (string? s, System.Globalization.NumberStyles style, IFormatProvider? provider, out short? result);
static member TryParse : string * System.Globalization.NumberStyles * IFormatProvider * int16 -> bool
Public Shared Function TryParse (s As String, style As NumberStyles, provider As IFormatProvider, ByRef result As Short) As Boolean
Parâmetros
- s
- String
Uma cadeia de caracteres que contém um número a ser convertido.A string containing a number to convert. A cadeia de caracteres é interpretada usando o estilo especificado por style
.The string is interpreted using the style specified by style
.
- style
- NumberStyles
Um combinação bit a bit de valores de enumeração que indica os elementos de estilo que podem estar presentes em s
.A bitwise combination of enumeration values that indicates the style elements that can be present in s
. Um valor típico a ser especificado é Integer.A typical value to specify is Integer.
- provider
- IFormatProvider
Um objeto que fornece informações de formatação específicas da cultura sobre s
.An object that supplies culture-specific formatting information about s
.
- result
- Int16
Quando esse método for retornado, conterá o equivalente do valor inteiro com sinal de 16 bits do número contido em s
, se a conversão tiver sido bem-sucedida, ou conterá zero, se a conversão tiver falhado.When this method returns, contains the 16-bit signed integer value equivalent to the number contained in s
, if the conversion succeeded, or zero if the conversion failed. A conversão falhará se o parâmetro s
for null
ou Empty, não estiver em um formato em conformidade com style
ou representar um número menor que MinValue ou maior que MaxValue.The conversion fails if the s
parameter is null
or Empty, is not in a format compliant with style
, or represents a number less than MinValue or greater than MaxValue. Este parâmetro é passado não inicializado; qualquer valor fornecido originalmente em result
será substituído.This parameter is passed uninitialized; any value originally supplied in result
will be overwritten.
Retornos
true
caso s
tenha sido convertido com êxito; do contrário, false
.true
if s
was converted successfully; otherwise, false
.
Exceções
style
não é um valor NumberStyles.style
is not a NumberStyles value.
- ou --or-
style
não é uma combinação de valores AllowHexSpecifier e HexNumber.style
is not a combination of AllowHexSpecifier and HexNumber values.
Exemplos
O exemplo a seguir chama o Int16.TryParse(String, NumberStyles, IFormatProvider, Int16) método com um número de valores de cadeia de caracteres diferentes.The following example calls the Int16.TryParse(String, NumberStyles, IFormatProvider, Int16) method with a number of different string values.
using System;
using System.Globalization;
public class StringParsing
{
public static void Main()
{
string numericString;
NumberStyles styles;
numericString = "10677";
styles = NumberStyles.Integer;
CallTryParse(numericString, styles);
numericString = "-30677";
styles = NumberStyles.None;
CallTryParse(numericString, styles);
numericString = "10345.00";
styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
CallTryParse(numericString, styles);
numericString = "10345.72";
styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
CallTryParse(numericString, styles);
numericString = "22,593";
styles = NumberStyles.Integer | NumberStyles.AllowThousands;
CallTryParse(numericString, styles);
numericString = "12E-01";
styles = NumberStyles.Integer | NumberStyles.AllowExponent;
CallTryParse(numericString, styles);
numericString = "12E03";
CallTryParse(numericString, styles);
numericString = "80c1";
CallTryParse(numericString, NumberStyles.HexNumber);
numericString = "0x80C1";
CallTryParse(numericString, NumberStyles.HexNumber);
}
private static void CallTryParse(string stringToConvert, NumberStyles styles)
{
short number;
bool result = Int16.TryParse(stringToConvert, styles,
CultureInfo.InvariantCulture, out number);
if (result)
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
else
Console.WriteLine("Attempted conversion of '{0}' failed.",
Convert.ToString(stringToConvert));
}
}
// The example displays the following output to the console:
// Converted '10677' to 10677.
// Attempted conversion of '-30677' failed.
// Converted '10345.00' to 10345.
// Attempted conversion of '10345.72' failed.
// Converted '22,593' to 22593.
// Attempted conversion of '12E-01' failed.
// Converted '12E03' to 12000.
// Converted '80c1' to -32575.
// Attempted conversion of '0x80C1' failed.
Imports System.Globalization
Module StringParsing
Public Sub Main()
Dim numericString As String
Dim styles As NumberStyles
numericString = "10677"
styles = NumberStyles.Integer
CallTryParse(numericString, styles)
numericString = "-30677"
styles = NumberStyles.None
CallTryParse(numericString, styles)
numericString = "10345.00"
styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
CallTryParse(numericString, styles)
numericString = "10345.72"
styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
CallTryParse(numericString, styles)
numericString = "22,593"
styles = NumberStyles.Integer Or NumberStyles.AllowThousands
CallTryParse(numericString, styles)
numericString = "12E-01"
styles = NumberStyles.Integer Or NumberStyles.AllowExponent
CallTryParse(numericString, styles)
numericString = "12E03"
CallTryParse(numericString, styles)
numericString = "80c1"
CallTryParse(numericString, NumberStyles.HexNumber)
numericString = "0x80C1"
CallTryParse(numericString, NumberStyles.HexNumber)
End Sub
Private Sub CallTryParse(stringToConvert As String, styles AS NumberStyles)
Dim number As Short
Dim result As Boolean = Int16.TryParse(stringToConvert, styles, _
CultureInfo.InvariantCulture, number)
If result Then
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
Else
Console.WriteLine("Attempted conversion of '{0}' failed.", _
Convert.ToString(stringToConvert))
End If
End Sub
End Module
' The example displays the following output to the console:
' Converted '10677' to 10677.
' Attempted conversion of '-30677' failed.
' Converted '10345.00' to 10345.
' Attempted conversion of '10345.72' failed.
' Converted '22,593' to 22593.
' Attempted conversion of '12E-01' failed.
' Converted '12E03' to 12000.
' Converted '80c1' to -32575.
' Attempted conversion of '0x80C1' failed.
Comentários
O Int16.TryParse(String, NumberStyles, IFormatProvider, Int16) método difere do Int16.Parse(String, NumberStyles, IFormatProvider) método retornando um valor booliano que indica se a operação de análise teve êxito em vez de retornar o valor analisado Int16 .The Int16.TryParse(String, NumberStyles, IFormatProvider, Int16) method differs from the Int16.Parse(String, NumberStyles, IFormatProvider) method by returning a Boolean value that indicates whether the parse operation succeeded instead of returning the parsed Int16 value. Ele elimina a necessidade de usar a identificação de exceções para testar um FormatException caso esse s
seja inválido e não possa ser analisado com êxito.It eliminates the need to use exception handling to test for a FormatException in the event that s
is invalid and cannot be successfully parsed.
O parâmetro style
define os elementos de estilo (como o espaço em branco ou um sinal positivo ou negativo) que são permitidos no parâmetro s
para que a operação de análise seja bem-sucedida.The style
parameter defines the style elements (such as white space or a positive or negative sign) that are allowed in the s
parameter for the parse operation to succeed. Ele deve ser uma combinação de sinalizadores de bits da enumeração NumberStyles.It must be a combination of bit flags from the NumberStyles enumeration. Dependendo do valor do estilo, o s
parâmetro pode incluir os seguintes elementos:Depending on the value of style, the s
parameter may include the following elements:
[ws][$][sign][digits,]digits[.fractional_digits][e[sign]digits][ws][ws][$][sign][digits,]digits[.fractional_digits][e[sign]digits][ws]
Ou, se o style
parâmetro incluir NumberStyles.AllowHexSpecifier :Or, if the style
parameter includes NumberStyles.AllowHexSpecifier:
[ws]hexdigits[ws][ws]hexdigits[ws]
Itens entre colchetes ([ e ]) são opcionais.Items in square brackets ([ and ]) are optional. A tabela a seguir descreve cada elemento.The following table describes each element.
ElementoElement | DescriçãoDescription |
---|---|
wsws | Espaço em branco opcional.Optional white space. 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.White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, or at the end of s if style includes the NumberStyles.AllowTrailingWhite flag. |
$ | Um símbolo de moeda específico de cultura.A culture-specific currency symbol. A posição na cadeia de caracteres é definida pela propriedade CurrencyPositivePattern do objeto NumberFormatInfo retornado pelo método GetFormat do parâmetro provider .Its position in the string is defined by the CurrencyPositivePattern property of the NumberFormatInfo object returned by the GetFormat method of the provider parameter. O símbolo de moeda pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowCurrencySymbol.The currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag. |
signsign | Um sinal opcional.An optional sign. |
dígitosdigits | Uma sequência de dígitos de 0 a 9.A sequence of digits from 0 through 9. |
,, | Um separador de milhares específico de cultura.A culture-specific thousands separator. O separador de milhares da cultura especificada por provider pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowThousands.The thousands separator of the culture specified by provider can appear in s if style includes the NumberStyles.AllowThousands flag. |
.. | Um símbolo de vírgula decimal específico de cultura.A culture-specific decimal point symbol. O símbolo da vírgula decimal da cultura especificada por provider pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowDecimalPoint.The decimal point symbol of the culture specified by provider can appear in s if style includes the NumberStyles.AllowDecimalPoint flag. |
fractional_digitsfractional_digits | Uma ou mais ocorrências de dígito 0.One or more occurrences of the digit 0. Os dígitos fracionários só podem ser exibidos em s caso style inclua o sinalizador NumberStyles.AllowDecimalPoint.Fractional digits can appear in s only if style includes the NumberStyles.AllowDecimalPoint flag. |
Orientale | O caractere 'e' ou 'E', que indica se o valor é representado na notação exponencial.The 'e' or 'E' character, which indicates that the value is represented in exponential notation. O parâmetro s pode representar um número em notação exponencial caso style inclua o sinalizador NumberStyles.AllowExponent.The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag. |
hexdigitshexdigits | Uma sequência de dígitos hexadecimais de 0 a f ou de 0 a F.A sequence of hexadecimal digits from 0 through f, or 0 through F. |
Observação
Todos os caracteres NUL (U + 0000) de encerramento s
são ignorados pela operação de análise, independentemente do valor do style
argumento.Any terminating NUL (U+0000) characters in s
are ignored by the parsing operation, regardless of the value of the style
argument.
Uma cadeia de caracteres apenas com dígitos decimais (que corresponde ao sinalizador NumberStyles.None ) sempre é analisada com êxito.A string with decimal digits only (which corresponds to the NumberStyles.None flag) always parses successfully. 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.Most of the remaining NumberStyles members control elements that may be but are not required to be present in this input string. A tabela a seguir indica como os membros NumberStyles individuais afetam os elementos que podem estar presentes em s
.The following table indicates how individual NumberStyles members affect the elements that may be present in s
.
Valores NumberStyles não compostosNon-composite NumberStyles values | Elementos permitidos em s além de dígitosElements permitted in s in addition to digits |
---|---|
NumberStyles.None | Somente dígitos decimais.Decimal digits only. |
NumberStyles.AllowDecimalPoint | O elemento de linguagem .The . e fractional_digits elementos.and fractional_digits elements. No entanto, fractional_digits deve consistir apenas de um ou mais 0 dígitos ou o método retorna false .However, fractional_digits must consist of only one or more 0 digits or the method returns false . |
NumberStyles.AllowExponent | O parâmetro s também pode usar notação exponencial.The s parameter can also use exponential notation. Se s representa um número em notação exponencial, ele deve representar um inteiro dentro do intervalo do Int16 tipo de dados sem um componente fracionário diferente de zero.If s represents a number in exponential notation, it must represent an integer within the range of the Int16 data type without a non-zero fractional component. |
NumberStyles.AllowLeadingWhite | O elemento WS no início de s.The ws element at the beginning of s. |
NumberStyles.AllowTrailingWhite | O elemento WS no final de s.The ws element at the end of s. |
NumberStyles.AllowLeadingSign | Um sinal pode aparecer antes dos dígitos.A sign can appear before digits. |
NumberStyles.AllowTrailingSign | Um sinal pode aparecer após dígitos.A sign can appear after digits. |
NumberStyles.AllowParentheses | O elemento sinal na forma de parênteses que incluem o valor numérico.The sign element in the form of parentheses enclosing the numeric value. |
NumberStyles.AllowThousands | O elemento , .The , element. |
NumberStyles.AllowCurrencySymbol | O $ elemento.The $ element. |
NumberStyles.Currency | Todos os elementos.All elements. O parâmetro s não pode representar um número hexadecimal ou um número na notação exponencial.The s parameter cannot represent a hexadecimal number or a number in exponential notation. |
NumberStyles.Float | O elemento WS no início ou no fim de s , assine o início de s e o .The ws element at the beginning or end of s , sign at the beginning of s , and the . símbolo.symbol. O parâmetro s também pode usar notação exponencial.The s parameter can also use exponential notation. |
NumberStyles.Number | Os elementos WS, Sign, milhar (,) e decimal (.).The ws, sign, thousands separator (,), and decimal point (.) elements. |
NumberStyles.Any | Todos os estilos, exceto caso s não possa representar um número hexadecimal.All styles, except s cannot represent a hexadecimal number. |
Se o NumberStyles.AllowHexSpecifier sinalizador for usado, s
deverá ser um valor hexadecimal sem um prefixo.If the NumberStyles.AllowHexSpecifier flag is used, s
must be a hexadecimal value without a prefix. Por exemplo, "9AF3" analisa com êxito, mas "0x9AF3" não.For example, "9AF3" parses successfully, but "0x9AF3" does not. Os únicos outros sinalizadores que podem estar presentes em style
são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite.The only other flags that can be present in style
are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. (A NumberStyles enumeração tem um estilo composto, NumberStyles.HexNumber , que inclui os dois sinalizadores de espaço em branco.)(The NumberStyles enumeration has a composite style, NumberStyles.HexNumber, that includes both white space flags.)
O parâmetro provider
é uma implementação de IFormatProvider, como um objeto CultureInfo ou um objeto NumberFormatInfo, cujo método GetFormat retorna um objeto NumberFormatInfo.The provider
parameter is an IFormatProvider implementation, such as a CultureInfo object or a NumberFormatInfo object, whose GetFormat method returns a NumberFormatInfo object. O objeto NumberFormatInfo fornece informações específicas da cultura sobre o formato de s
.The NumberFormatInfo object provides culture-specific information about the format of s
. Caso provider
seja null
, o objeto NumberFormatInfo da cultura atual é usado.If provider
is null
, the NumberFormatInfo object for the current culture is used.
Confira também
- Parse
- NumberStyles
- ToString()
- Análise de cadeias de caracteres numéricas no .NETParsing Numeric Strings in .NET
Aplica-se a
TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int16)
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.Converts the span representation of a number in a specified style and culture-specific format to its 16-bit signed integer equivalent. Um valor retornado indica se a conversão foi bem-sucedida ou falhou.A return value indicates whether the conversion succeeded or failed.
public:
static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] short % result);
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider? provider, out short result);
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider provider, out short result);
static member TryParse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider * int16 -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), style As NumberStyles, provider As IFormatProvider, ByRef result As Short) As Boolean
Parâmetros
- s
- ReadOnlySpan<Char>
Um intervalo que contém os caracteres que representam o número a ser convertido.A span containing the characters representing the number to convert. O intervalo é interpretado usando o estilo especificado por style
.The span is interpreted using the style specified by style
.
- style
- NumberStyles
Um combinação bit a bit de valores de enumeração que indica os elementos de estilo que podem estar presentes em s
.A bitwise combination of enumeration values that indicates the style elements that can be present in s
. Um valor típico a ser especificado é Integer.A typical value to specify is Integer.
- provider
- IFormatProvider
Um objeto que fornece informações de formatação específicas da cultura sobre s
.An object that supplies culture-specific formatting information about s
.
- result
- Int16
Quando esse método for retornado, conterá o equivalente do valor inteiro com sinal de 16 bits do número contido em s
, se a conversão tiver sido bem-sucedida, ou conterá zero, se a conversão tiver falhado.When this method returns, contains the 16-bit signed integer value equivalent to the number contained in s
, if the conversion succeeded, or zero if the conversion failed. A conversão falhará se o parâmetro s
for null
ou Empty, não estiver em um formato em conformidade com style
ou representar um número menor que MinValue ou maior que MaxValue.The conversion fails if the s
parameter is null
or Empty, is not in a format compliant with style
, or represents a number less than MinValue or greater than MaxValue. Este parâmetro é passado não inicializado; qualquer valor fornecido originalmente em result
será substituído.This parameter is passed uninitialized; any value originally supplied in result
will be overwritten.
Retornos
true
caso s
tenha sido convertido com êxito; do contrário, false
.true
if s
was converted successfully; otherwise, false
.