Byte.TryParse Método
Definição
Tenta converter a representação de cadeia de caracteres de um número em seu Byte equivalente e retorna um valor que indica se a conversão foi bem-sucedida.Tries to convert the string representation of a number to its Byte equivalent, and returns a value that indicates whether the conversion succeeded.
Sobrecargas
TryParse(String, Byte) |
Tenta converter a representação de cadeia de caracteres de um número em seu Byte equivalente e retorna um valor que indica se a conversão foi bem-sucedida.Tries to convert the string representation of a number to its Byte equivalent, and returns a value that indicates whether the conversion succeeded. |
TryParse(ReadOnlySpan<Char>, Byte) |
Tenta converter a representação de intervalo de um número em seu Byte equivalente e retorna um valor que indica se a conversão foi bem-sucedida.Tries to convert the span representation of a number to its Byte equivalent, and returns a value that indicates whether the conversion succeeded. |
TryParse(String, NumberStyles, IFormatProvider, Byte) |
Converte a representação de cadeia de caracteres de um número com um estilo especificado e um formato específico à cultura para seu Byte equivalente.Converts the string representation of a number in a specified style and culture-specific format to its Byte 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, Byte) |
Converte a representação de intervalo de um número com um estilo especificado e um formato específico à cultura para seu Byte equivalente.Converts the span representation of a number in a specified style and culture-specific format to its Byte 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, Byte)
Tenta converter a representação de cadeia de caracteres de um número em seu Byte equivalente e retorna um valor que indica se a conversão foi bem-sucedida.Tries to convert the string representation of a number to its Byte equivalent, and returns a value that indicates whether the conversion succeeded.
public:
static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] System::Byte % result);
public static bool TryParse (string s, out byte result);
public static bool TryParse (string? s, out byte? result);
static member TryParse : string * byte -> bool
Public Shared Function TryParse (s As String, ByRef result As Byte) As Boolean
Parâmetros
- s
- String
Uma cadeia de caracteres que contém um número a ser convertido.A string that contains a number to convert.
- result
- Byte
Quando esse método retorna, ele contém o valor Byte equivalente ao número contido em s
, caso a conversão seja bem-sucedida ou zero caso a conversão falhe.When this method returns, contains the Byte value equivalent to the number contained in s
if the conversion succeeded, or zero if the conversion failed. 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 TryParse(String, Byte) método com um número de valores de cadeia de caracteres diferentes.The following example calls the TryParse(String, Byte) method with a number of different string values.
using namespace System;
void main()
{
array<String^>^ byteStrings = gcnew array<String^> { nullptr, String::Empty,
"1024", "100.1", "100",
"+100", "-100", "000000000000000100",
"00,100", " 20 ", "FF", "0x1F" };
Byte byteValue;
for each (String^ byteString in byteStrings) {
bool result = Byte::TryParse(byteString, byteValue);
if (result)
Console::WriteLine("Converted '{0}' to {1}",
byteString, byteValue);
else
Console::WriteLine("Attempted conversion of '{0}' failed.",
byteString);
}
}
// The example displays the following output:
// Attempted conversion of '' failed.
// Attempted conversion of '' failed.`
// Attempted conversion of '1024' failed.
// Attempted conversion of '100.1' failed.
// Converted '100' to 100
// Converted '+100' to 100
// Attempted conversion of '-100' failed.
// Converted '000000000000000100' to 100
// Attempted conversion of '00,100' failed.
// Converted ' 20 ' to 20
// Attempted conversion of 'FF' failed.
// Attempted conversion of '0x1F' failed.}
using System;
public class ByteConversion
{
public static void Main()
{
string[] byteStrings = { null, string.Empty, "1024",
"100.1", "100", "+100", "-100",
"000000000000000100", "00,100",
" 20 ", "FF", "0x1F" };
foreach (var byteString in byteStrings)
{
CallTryParse(byteString);
}
}
private static void CallTryParse(string stringToConvert)
{
byte byteValue;
bool success = Byte.TryParse(stringToConvert, out byteValue);
if (success)
{
Console.WriteLine("Converted '{0}' to {1}",
stringToConvert, byteValue);
}
else
{
Console.WriteLine("Attempted conversion of '{0}' failed.",
stringToConvert);
}
}
}
// The example displays the following output to the console:
// Attempted conversion of '' failed.
// Attempted conversion of '' failed.
// Attempted conversion of '1024' failed.
// Attempted conversion of '100.1' failed.
// Converted '100' to 100
// Converted '+100' to 100
// Attempted conversion of '-100' failed.
// Converted '000000000000000100' to 100
// Attempted conversion of '00,100' failed.
// Converted ' 20 ' to 20
// Attempted conversion of 'FF' failed.
// Attempted conversion of '0x1F' failed.
Module ByteConversion
Public Sub Main()
Dim byteStrings() As String = { Nothing, String.Empty, "1024",
"100.1", "100", "+100", "-100",
"000000000000000100", "00,100",
" 20 ", "FF", "0x1F"}
For Each byteString As String In byteStrings
CallTryParse(byteString)
Next
End Sub
Private Sub CallTryParse(stringToConvert As String)
Dim byteValue As Byte
Dim success As Boolean = Byte.TryParse(stringToConvert, byteValue)
If success Then
Console.WriteLine("Converted '{0}' to {1}", _
stringToConvert, byteValue)
Else
Console.WriteLine("Attempted conversion of '{0}' failed.", _
stringToConvert)
End If
End Sub
End Module
' The example displays the following output to the console:
' Attempted conversion of '' failed.
' Attempted conversion of '' failed.
' Attempted conversion of '1024' failed.
' Attempted conversion of '100.1' failed.
' Converted '100' to 100
' Converted '+100' to 100
' Attempted conversion of '-100' failed.
' Converted '000000000000000100' to 100
' Attempted conversion of '00,100' failed.
' Converted ' 20 ' to 20
' Attempted conversion of 'FF' failed.
' Attempted conversion of '0x1F' failed.
Comentários
A conversão falhará e o método retornará false
se o s
parâmetro não estiver no formato correto, se for null
ou String.Empty , ou se ele representar um número menor MinValue ou maior que MaxValue .The conversion fails and the method returns false
if the s
parameter is not in the correct format, if it is null
or String.Empty, or if it represents a number less than MinValue or greater than MaxValue.
O Byte.TryParse(String, Byte) método é semelhante ao Byte.Parse(String) método, exceto que não TryParse(String, Byte) gera uma exceção se a conversão falhar.The Byte.TryParse(String, Byte) method is similar to the Byte.Parse(String) method, except that TryParse(String, Byte) does not throw an exception if the conversion fails.
O s
parâmetro deve ser a representação de cadeia de caracteres de um número no seguinte formato:The s
parameter should be the string representation of a number in the following form:
[ws][sign]digits[ws]
Os elementos entre colchetes ([ e ]) são opcionais.Elements 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 positivo opcional, conforme especificado pela NumberFormatInfo.PositiveSign propriedade da cultura atual.An optional positive sign, as specified by the NumberFormatInfo.PositiveSign property of the current culture. |
dígitosdigits | Uma sequência de dígitos decimais que varia de 0 a 9.A sequence of decimal digits that range from 0 to 9. |
O parâmetro s
é interpretado usando-se o estilo Integer.The s
parameter is interpreted using the Integer style. Além dos dígitos decimais do valor de byte, somente espaços à esquerda e à direita, juntamente com um sinal à esquerda, são permitidos.In addition to the byte value's decimal digits, only leading and trailing spaces together with a leading sign are allowed. (Se o sinal estiver presente, ele deverá ser um sinal positivo ou o método lançará um OverflowException .) 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 Byte.Parse(String, NumberStyles, IFormatProvider) método.(If the sign is present, it must be a positive sign or the method throws an OverflowException.) To explicitly define the style elements together with the culture-specific formatting information that can be present in s
, use the Byte.Parse(String, NumberStyles, IFormatProvider) method.
O s
parâmetro é analisado usando as informações de formatação em um NumberFormatInfo objeto para a cultura atual.The s
parameter is parsed using the formatting information in a NumberFormatInfo object for the current culture. Para obter mais informações, consulte NumberFormatInfo.CurrentInfo.For more information, see NumberFormatInfo.CurrentInfo.
Essa sobrecarga do Byte.TryParse(String, Byte) método interpreta todos os dígitos no s
parâmetro como dígitos decimais.This overload of the Byte.TryParse(String, Byte) 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 Byte.TryParse(String, NumberStyles, IFormatProvider, Byte) sobrecarga.To parse the string representation of a hexadecimal number, call the Byte.TryParse(String, NumberStyles, IFormatProvider, Byte) overload.
Confira também
- 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>, Byte)
public:
static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] System::Byte % result);
public static bool TryParse (ReadOnlySpan<char> s, out byte result);
static member TryParse : ReadOnlySpan<char> * byte -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As Byte) 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
- Byte
Quando esse método retorna, ele contém o valor Byte equivalente ao número contido em s
, caso a conversão seja bem-sucedida ou zero caso a conversão falhe.When this method returns, contains the Byte value equivalent to the number contained in s
if the conversion succeeded, or zero if the conversion failed. 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, Byte)
Converte a representação de cadeia de caracteres de um número com um estilo especificado e um formato específico à cultura para seu Byte equivalente.Converts the string representation of a number in a specified style and culture-specific format to its Byte 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] System::Byte % result);
public static bool TryParse (string s, System.Globalization.NumberStyles style, IFormatProvider provider, out byte result);
public static bool TryParse (string? s, System.Globalization.NumberStyles style, IFormatProvider? provider, out byte? result);
static member TryParse : string * System.Globalization.NumberStyles * IFormatProvider * byte -> bool
Public Shared Function TryParse (s As String, style As NumberStyles, provider As IFormatProvider, ByRef result As Byte) 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
. Caso provider
seja null
, a cultura atual do thread é usada.If provider
is null
, the thread current culture is used.
- result
- Byte
Quando esse método for retornado, ele conterá o equivalente do valor inteiro sem sinal de 8 bits do número contido em s
, se a conversão tiver sido bem-sucedida, ou zero, se a conversão tiver falhado.When this method returns, contains the 8-bit unsigned 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
.
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 TryParse(String, NumberStyles, IFormatProvider, Byte) método com um número de valores de cadeia de caracteres diferentes.The following example calls the TryParse(String, NumberStyles, IFormatProvider, Byte) method with a number of different string values.
using namespace System;
using namespace System::Globalization;
void CallTryParse(String^ byteString, NumberStyles styles);
void main()
{
String^ byteString;
NumberStyles styles;
byteString = "1024";
styles = NumberStyles::Integer;
CallTryParse(byteString, styles);
byteString = "100.1";
styles = NumberStyles::Integer | NumberStyles::AllowDecimalPoint;
CallTryParse(byteString, styles);
byteString = "100.0";
CallTryParse(byteString, styles);
byteString = "+100";
styles = NumberStyles::Integer | NumberStyles::AllowLeadingSign
| NumberStyles::AllowTrailingSign;
CallTryParse(byteString, styles);
byteString = "-100";
CallTryParse(byteString, styles);
byteString = "000000000000000100";
CallTryParse(byteString, styles);
byteString = "00,100";
styles = NumberStyles::Integer | NumberStyles::AllowThousands;
CallTryParse(byteString, styles);
byteString = "2E+3 ";
styles = NumberStyles::Integer | NumberStyles::AllowExponent;
CallTryParse(byteString, styles);
byteString = "FF";
styles = NumberStyles::HexNumber;
CallTryParse(byteString, styles);
byteString = "0x1F";
CallTryParse(byteString, styles);
}
void CallTryParse(String^ stringToConvert, NumberStyles styles)
{
Byte byteValue;
bool result = Byte::TryParse(stringToConvert, styles,
(IFormatProvider^) nullptr , byteValue);
if (result)
Console::WriteLine("Converted '{0}' to {1}",
stringToConvert, byteValue);
else
Console::WriteLine("Attempted conversion of '{0}' failed.",
stringToConvert);
}
// The example displays the following output:
// Attempted conversion of '1024' failed.
// Attempted conversion of '100.1' failed.
// Converted '100.0' to 100
// Converted '+100' to 100
// Attempted conversion of '-100' failed.
// Converted '000000000000000100' to 100
// Converted '00,100' to 100
// Attempted conversion of '2E+3 ' failed.
// Converted 'FF' to 255
// Attempted conversion of '0x1F' failed.}
using System;
using System.Globalization;
public class ByteConversion2
{
public static void Main()
{
string byteString;
NumberStyles styles;
byteString = "1024";
styles = NumberStyles.Integer;
CallTryParse(byteString, styles);
byteString = "100.1";
styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
CallTryParse(byteString, styles);
byteString = "100.0";
CallTryParse(byteString, styles);
byteString = "+100";
styles = NumberStyles.Integer | NumberStyles.AllowLeadingSign
| NumberStyles.AllowTrailingSign;
CallTryParse(byteString, styles);
byteString = "-100";
CallTryParse(byteString, styles);
byteString = "000000000000000100";
CallTryParse(byteString, styles);
byteString = "00,100";
styles = NumberStyles.Integer | NumberStyles.AllowThousands;
CallTryParse(byteString, styles);
byteString = "2E+3 ";
styles = NumberStyles.Integer | NumberStyles.AllowExponent;
CallTryParse(byteString, styles);
byteString = "FF";
styles = NumberStyles.HexNumber;
CallTryParse(byteString, styles);
byteString = "0x1F";
CallTryParse(byteString, styles);
}
private static void CallTryParse(string stringToConvert, NumberStyles styles)
{
Byte byteValue;
bool result = Byte.TryParse(stringToConvert, styles,
null as IFormatProvider, out byteValue);
if (result)
Console.WriteLine("Converted '{0}' to {1}",
stringToConvert, byteValue);
else
Console.WriteLine("Attempted conversion of '{0}' failed.",
stringToConvert.ToString());
}
}
// The example displays the following output to the console:
// Attempted conversion of '1024' failed.
// Attempted conversion of '100.1' failed.
// Converted '100.0' to 100
// Converted '+100' to 100
// Attempted conversion of '-100' failed.
// Converted '000000000000000100' to 100
// Converted '00,100' to 100
// Attempted conversion of '2E+3 ' failed.
// Converted 'FF' to 255
// Attempted conversion of '0x1F' failed.
Imports System.Globalization
Module ByteConversion2
Public Sub Main()
Dim byteString As String
Dim styles As NumberStyles
byteString = "1024"
styles = NumberStyles.Integer
CallTryParse(byteString, styles)
byteString = "100.1"
styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
CallTryParse(byteString, styles)
byteString = "100.0"
CallTryParse(byteString, styles)
byteString = "+100"
styles = NumberStyles.Integer Or NumberStyles.AllowLeadingSign _
Or NumberStyles.AllowTrailingSign
CallTryParse(byteString, styles)
byteString = "-100"
CallTryParse(byteString, styles)
byteString = "000000000000000100"
CallTryParse(byteString, styles)
byteString = "00,100"
styles = NumberStyles.Integer Or NumberStyles.AllowThousands
CallTryParse(byteString, styles)
byteString = "2E+3 "
styles = NumberStyles.Integer Or NumberStyles.AllowExponent
CallTryParse(byteString, styles)
byteString = "FF"
styles = NumberStyles.HexNumber
CallTryParse(byteString, styles)
byteString = "0x1F"
CallTryParse(byteString, styles)
End Sub
Private Sub CallTryParse(stringToConvert As String, styles As NumberStyles)
Dim byteValue As Byte
Dim result As Boolean = Byte.TryParse(stringToConvert, styles, Nothing, _
byteValue)
If result Then
Console.WriteLine("Converted '{0}' to {1}", _
stringToConvert, byteValue)
Else
If stringToConvert Is Nothing Then stringToConvert = ""
Console.WriteLine("Attempted conversion of '{0}' failed.", _
stringToConvert.ToString())
End If
End Sub
End Module
' The example displays the following output to the console:
' Attempted conversion of '1024' failed.
' Attempted conversion of '100.1' failed.
' Converted '100.0' to 100
' Converted '+100' to 100
' Attempted conversion of '-100' failed.
' Converted '000000000000000100' to 100
' Converted '00,100' to 100
' Attempted conversion of '2E+3 ' failed.
' Converted 'FF' to 255
' Attempted conversion of '0x1F' failed.
Comentários
O TryParse método é como o Parse método, exceto pelo fato de o TryParse método não lançar uma exceção se a conversão falhar.The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails.
O s
parâmetro é analisado usando as informações de formatação em um NumberFormatInfo objeto fornecido pelo provider
parâmetro.The s
parameter is parsed using the formatting information in a NumberFormatInfo object supplied by the provider
parameter.
O parâmetro Style define os elementos de estilo (como um espaço em branco ou o sinal positivo) que são permitidos no s
parâmetro para que a operação de análise tenha sucesso.The style parameter defines the style elements (such as white space or the positive 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 de style
, o parâmetro s
pode incluir os seguintes elementos:Depending on the value of style
, the s
parameter may include the following elements:
Federation [$] [sign] dígitos [.fractional_digits] [e [sign] dígitos] [ws][ws][$][sign]digits[.fractional_digits][e[sign]digits][ws]
Ou, se o style
parâmetro incluir AllowHexSpecifier :Or, if the style
parameter includes AllowHexSpecifier:
[ws]hexdigits[ws][ws]hexdigits[ws]
Os elementos entre colchetes ([e]) são opcionais.Elements 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 aparecer no início de s se style incluir o NumberStyles.AllowLeadingWhite sinalizador ou no final de s se o estilo incluir o NumberStyles.AllowTrailingWhite sinalizador.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 NumberFormatInfo.CurrencyPositivePattern do objeto NumberFormatInfo retornado pelo método GetFormat do parâmetro provider .Its position in the string is defined by the NumberFormatInfo.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 positivo opcional.An optional positive sign. (A operação de análise falhará se um sinal negativo estiver presente no s .) O sinal pode aparecer no início de s se style incluir o NumberStyles.AllowLeadingSign sinalizador ou no final de s se style incluir o NumberStyles.AllowTrailingSign sinalizador.(The parse operation fails if a negative sign is present in s .) The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, or at the end of s if style includes the NumberStyles.AllowTrailingSign flag. |
dígitosdigits | Uma sequência de dígitos de 0 a 9.A sequence of digits from 0 through 9. |
.. | 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 que o valor é representado em 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 estilo NumberStyles.None ) sempre é analisada com êxito.A string with decimal digits only (which corresponds to the NumberStyles.None style) 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 Byte 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 Byte 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 positivo pode aparecer antes dos dígitos.A positive sign can appear before digits. |
NumberStyles.AllowTrailingSign | Um sinal positivo pode aparecer após dígitos.A positive sign can appear after digits. |
NumberStyles.AllowParentheses | Embora haja suporte para esse sinalizador, o método retorna false se os parênteses estão presentes no s .Although this flag is supported, the method returns false if parentheses are present in s . |
NumberStyles.AllowThousands | Embora o símbolo do separador de grupo possa aparecer no s , ele pode ser precedido por apenas um ou mais 0 dígitos.Although the group separator symbol can appear in s , it can be preceded by only one or more 0 digits. |
NumberStyles.AllowCurrencySymbol | O $ elemento.The $ element. |
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, "F3" analisa com êxito, mas "0xF3" não.For example, "F3" parses successfully, but "0xF3" 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 enumeração de NumberStyles tem um estilo de número composto, NumberStyles.HexNumber, que inclui ambos os sinalizadores de espaço em branco.)(The NumberStyles enumeration has a composite number 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
.
Confira também
- ToString()
- MaxValue
- MinValue
- NumberStyles
- NumberFormatInfo
- IFormatProvider
- Análise de cadeias de caracteres numéricas no .NETParsing Numeric Strings in .NET
Aplica-se a
TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Byte)
Converte a representação de intervalo de um número com um estilo especificado e um formato específico à cultura para seu Byte equivalente.Converts the span representation of a number in a specified style and culture-specific format to its Byte 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] System::Byte % result);
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider? provider, out byte result);
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider provider, out byte result);
static member TryParse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider * byte -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), style As NumberStyles, provider As IFormatProvider, ByRef result As Byte) 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 Integer.The span is interpreted using the Integer 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
. Caso provider
seja null
, a cultura atual do thread é usada.If provider
is null
, the thread current culture is used.
- result
- Byte
Quando esse método for retornado, ele conterá o equivalente do valor inteiro sem sinal de 8 bits do número contido em s
, se a conversão tiver sido bem-sucedida, ou zero, se a conversão tiver falhado.When this method returns, contains the 8-bit unsigned 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
.