SByte.Parse Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Converte a representação da cadeia de um número para o seu equivalente inteiro com sinal de 8 bits.
Sobrecargas
| Name | Description |
|---|---|
| Parse(String) |
Converte a representação da cadeia de um número para o seu equivalente inteiro com sinal de 8 bits. |
| Parse(ReadOnlySpan<Byte>, IFormatProvider) |
Analisa um intervalo de caracteres UTF-8 num valor. |
| Parse(ReadOnlySpan<Char>, IFormatProvider) |
Divide um intervalo de caracteres num valor. |
| Parse(String, NumberStyles) |
Converte a representação da cadeia de um número num estilo especificado para o seu equivalente inteiro com sinal de 8 bits. |
| Parse(String, IFormatProvider) |
Converte a representação da cadeia de um número num formato específico de cultura para o seu equivalente inteiro com sinal de 8 bits. |
| Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider) |
Analisa um intervalo de caracteres UTF-8 num valor. |
| Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) |
Converte a representação span de um número que está num estilo especificado e formato específico de cultura para o seu equivalente com sinal de 8 bits. |
| Parse(String, NumberStyles, IFormatProvider) |
Converte a representação da cadeia de um número que está num estilo especificado e formato específico de cultura para o seu equivalente com sinal de 8 bits. |
Parse(String)
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
Importante
Esta API não está em conformidade com CLS.
- Alternativa em conformidade com CLS
- System.Int16.Parse(String)
Converte a representação da cadeia de um número para o seu equivalente inteiro com sinal de 8 bits.
public:
static System::SByte Parse(System::String ^ s);
[System.CLSCompliant(false)]
public static sbyte Parse(string s);
public static sbyte Parse(string s);
[<System.CLSCompliant(false)>]
static member Parse : string -> sbyte
static member Parse : string -> sbyte
Public Shared Function Parse (s As String) As SByte
Parâmetros
- s
- String
Uma cadeia que representa um número a converter. A corda é interpretada usando o Integer estilo.
Devoluções
Um inteiro com sinal de 8 bits que é equivalente ao número contido no s parâmetro.
- Atributos
Exceções
s é null.
s não consiste num sinal opcional seguido de uma sequência de dígitos (de zero a nove).
s representa um número inferior a SByte.MinValue ou superior a SByte.MaxValue.
Exemplos
O exemplo seguinte demonstra como converter um valor de cadeia de caracteres num valor de byte assinado usando o Parse método. O valor resultante do byte assinado é então apresentado na consola.
// Define an array of numeric strings.
string[] values = { "-16", " -3", "+ 12", " +12 ", " 12 ",
"+120", "(103)", "192", "-160" };
// Parse each string and display the result.
foreach (string value in values)
{
try {
Console.WriteLine("Converted '{0}' to the SByte value {1}.",
value, SByte.Parse(value));
}
catch (FormatException) {
Console.WriteLine("'{0}' cannot be parsed successfully by SByte type.",
value);
}
catch (OverflowException) {
Console.WriteLine("'{0}' is out of range of the SByte type.",
value);
}
}
// The example displays the following output:
// Converted '-16' to the SByte value -16.
// Converted ' -3' to the SByte value -3.
// '+ 12' cannot be parsed successfully by SByte type.
// Converted ' +12 ' to the SByte value 12.
// Converted ' 12 ' to the SByte value 12.
// Converted '+120' to the SByte value 120.
// '(103)' cannot be parsed successfully by SByte type.
// '192' is out of range of the SByte type.
// '-160' is out of range of the SByte type.
open System
// Define an array of numeric strings.
let values =
[| "-16"; " -3"; "+ 12"; " +12 "; " 12 "
"+120"; "(103)"; "192"; "-160" |]
// Parse each string and display the result.
for value in values do
try
printfn $"Converted '{value}' to the SByte value {SByte.Parse value}."
with
| :? FormatException ->
printfn $"'{value}' cannot be parsed successfully by SByte type."
| :? OverflowException ->
printfn $"'{value}' is out of range of the SByte type."
// The example displays the following output:
// Converted '-16' to the SByte value -16.
// Converted ' -3' to the SByte value -3.
// '+ 12' cannot be parsed successfully by SByte type.
// Converted ' +12 ' to the SByte value 12.
// Converted ' 12 ' to the SByte value 12.
// Converted '+120' to the SByte value 120.
// '(103)' cannot be parsed successfully by SByte type.
// '192' is out of range of the SByte type.
// '-160' is out of range of the SByte type.
' Define an array of numeric strings.
Dim values() As String = { "-16", " -3", "+ 12", " +12 ", " 12 ", _
"+120", "(103)", "192", "-160" }
' Parse each string and display the result.
For Each value As String In values
Try
Console.WriteLine("Converted '{0}' to the SByte value {1}.", _
value, SByte.Parse(value))
Catch e As FormatException
Console.WriteLine("'{0}' cannot be parsed successfully by SByte type.", _
value)
Catch e As OverflowException
Console.WriteLine("'{0}' is out of range of the SByte type.", _
value)
End Try
Next
' The example displays the following output:
' Converted '-16' to the SByte value -16.
' Converted ' -3' to the SByte value -3.
' '+ 12' cannot be parsed successfully by SByte type.
' Converted ' +12 ' to the SByte value 12.
' Converted ' 12 ' to the SByte value 12.
' Converted '+120' to the SByte value 120.
' '(103)' cannot be parsed successfully by SByte type.
' '192' is out of range of the SByte type.
' '-160' is out of range of the SByte type.
Observações
O s parâmetro contém um número da forma:
[ws][sinal]dígitos[ws]
Os elementos entre parênteses retos ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.
| Elemento | Descrição |
|---|---|
| ws | Espaço em branco opcional. |
| assinar | Um sinal opcional. |
| dígitos | Uma sequência de dígitos que varia de 0 a 9. |
O s parâmetro é interpretado usando o NumberStyles.Integer estilo. Para além dos dígitos decimais do valor do byte, apenas espaços à esquerda e à frente com sinal positivo ou negativo à esquerda são permitidos. Para definir explicitamente os elementos de estilo que podem estar presentes em s, use o Parse(String, NumberStyles) ou o Parse(String, NumberStyles, IFormatProvider) método.
O s parâmetro é analisado usando a informação de formatação em a NumberFormatInfo que é inicializada para a cultura do sistema atual. Para obter mais informações, veja NumberFormatInfo.CurrentInfo. Para analisar uma cadeia usando a informação de formatação de outra cultura, use o Parse(String, NumberStyles, IFormatProvider) método.
Ver também
Aplica-se a
Parse(ReadOnlySpan<Byte>, IFormatProvider)
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
Analisa um intervalo de caracteres UTF-8 num valor.
public:
static System::SByte Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<System::SByte>::Parse;
public static sbyte Parse(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> sbyte
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As SByte
Parâmetros
- utf8Text
- ReadOnlySpan<Byte>
A extensão de caracteres UTF-8 para analisar.
- provider
- IFormatProvider
Um objeto que fornece informação de formatação específica da cultura sobre utf8Text.
Devoluções
O resultado da análise sintática utf8Text.
Implementações
Aplica-se a
Parse(ReadOnlySpan<Char>, IFormatProvider)
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
Divide um intervalo de caracteres num valor.
public:
static System::SByte Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<System::SByte>::Parse;
public static sbyte Parse(ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> sbyte
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As SByte
Parâmetros
- s
- ReadOnlySpan<Char>
O número de personagens a analisar.
- provider
- IFormatProvider
Um objeto que fornece informação de formatação específica da cultura sobre s.
Devoluções
O resultado da análise sintática s.
Implementações
Aplica-se a
Parse(String, NumberStyles)
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
Importante
Esta API não está em conformidade com CLS.
- Alternativa em conformidade com CLS
- System.Int16.Parse(String)
Converte a representação da cadeia de um número num estilo especificado para o seu equivalente inteiro com sinal de 8 bits.
public:
static System::SByte Parse(System::String ^ s, System::Globalization::NumberStyles style);
[System.CLSCompliant(false)]
public static sbyte Parse(string s, System.Globalization.NumberStyles style);
public static sbyte Parse(string s, System.Globalization.NumberStyles style);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles -> sbyte
static member Parse : string * System.Globalization.NumberStyles -> sbyte
Public Shared Function Parse (s As String, style As NumberStyles) As SByte
Parâmetros
- s
- String
Uma cadeia que contém um número a converter. A cadeia é interpretada usando o estilo especificado por style.
- style
- NumberStyles
Uma combinação bit a bit dos valores de enumeração que indica os elementos de estilo que podem estar presentes em s. Um valor típico a especificar é Integer.
Devoluções
Um inteiro com sinal de 8 bits que é equivalente ao número especificado em s.
- Atributos
Exceções
s é null.
s não está num formato compatível com style.
s representa um número inferior a SByte.MinValue ou superior a SByte.MaxValue.
-ou-
s inclui dígitos fracionados e não nulos.
style não é um NumberStyles valor.
-ou-
style não é uma combinação de AllowHexSpecifier valores e HexNumber .
Exemplos
O exemplo seguinte analisa as representações das cadeias de SByte valores com o Parse(String, NumberStyles) método. A cultura atual para o exemplo é en-US.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
NumberStyles style;
sbyte number;
// Parse value with no styles allowed.
string[] values1 = { " 121 ", "121", "-121" };
style = NumberStyles.None;
Console.WriteLine("Styles: {0}", style.ToString());
foreach (string value in values1)
{
try {
number = SByte.Parse(value, style);
Console.WriteLine(" Converted '{0}' to {1}.", value, number);
}
catch (FormatException) {
Console.WriteLine(" Unable to parse '{0}'.", value);
}
}
Console.WriteLine();
// Parse value with trailing sign.
style = NumberStyles.Integer | NumberStyles.AllowTrailingSign;
string[] values2 = { " 103+", " 103 +", "+103", "(103)", " +103 " };
Console.WriteLine("Styles: {0}", style.ToString());
foreach (string value in values2)
{
try {
number = SByte.Parse(value, style);
Console.WriteLine(" Converted '{0}' to {1}.", value, number);
}
catch (FormatException) {
Console.WriteLine(" Unable to parse '{0}'.", value);
}
catch (OverflowException) {
Console.WriteLine(" '{0}' is out of range of the SByte type.", value);
}
}
Console.WriteLine();
}
}
// The example displays the following output:
// Styles: None
// Unable to parse ' 121 '.
// Converted '121' to 121.
// Unable to parse '-121'.
//
// Styles: Integer, AllowTrailingSign
// Converted ' 103+' to 103.
// Converted ' 103 +' to 103.
// Converted '+103' to 103.
// Unable to parse '(103)'.
// Converted ' +103 ' to 103.
open System
open System.Globalization
// Parse value with no styles allowed.
let values1 = [| " 121 "; "121"; "-121" |]
let style = NumberStyles.None
printfn $"Styles: {style}"
for value in values1 do
try
let number = SByte.Parse(value, style)
printfn $" Converted '{value}' to {number}."
with :? FormatException ->
printfn $" Unable to parse '{value}'."
printfn ""
// Parse value with trailing sign.
let style2 = NumberStyles.Integer ||| NumberStyles.AllowTrailingSign
let values2 = [| " 103+"; " 103 +"; "+103"; "(103)"; " +103 " |]
printfn $"Styles: {style2}"
for value in values2 do
try
let number = SByte.Parse(value, style2)
printfn $" Converted '{value}' to {number}."
with
| :? FormatException ->
printfn $" Unable to parse '{value}'."
| :? OverflowException ->
printfn $" '{value}' is out of range of the SByte type."
printfn ""
// The example displays the following output:
// Styles: None
// Unable to parse ' 121 '.
// Converted '121' to 121.
// Unable to parse '-121'.
//
// Styles: Integer, AllowTrailingSign
// Converted ' 103+' to 103.
// Converted ' 103 +' to 103.
// Converted '+103' to 103.
// Unable to parse '(103)'.
// Converted ' +103 ' to 103.
Imports System.Globalization
Module Example
Public Sub Main()
Dim style As NumberStyles
Dim number As SByte
' Parse value with no styles allowed.
Dim values1() As String = { " 121 ", "121", "-121" }
style = NumberStyles.None
Console.WriteLine("Styles: {0}", style.ToString())
For Each value As String In values1
Try
number = SByte.Parse(value, style)
Console.WriteLine(" Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine(" Unable to parse '{0}'.", value)
End Try
Next
Console.WriteLine()
' Parse value with trailing sign.
style = NumberStyles.Integer Or NumberStyles.AllowTrailingSign
Dim values2() As String = { " 103+", " 103 +", "+103", "(103)", " +103 " }
Console.WriteLine("Styles: {0}", style.ToString())
For Each value As String In values2
Try
number = SByte.Parse(value, style)
Console.WriteLine(" Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine(" Unable to parse '{0}'.", value)
Catch e As OverflowException
Console.WriteLine(" '{0}' is out of range of the SByte type.", value)
End Try
Next
Console.WriteLine()
End Sub
End Module
' The example displays the following output:
' Styles: None
' Unable to parse ' 121 '.
' Converted '121' to 121.
' Unable to parse '-121'.
'
' Styles: Integer, AllowTrailingSign
' Converted ' 103+' to 103.
' Converted ' 103 +' to 103.
' Converted '+103' to 103.
' Unable to parse '(103)'.
' Converted ' +103 ' to 103.
Observações
O style parâmetro define os elementos de estilo (como espaços em branco ou o símbolo de sinal positivo ou negativo) que são permitidos no s parâmetro para que a operação de análise sintética tenha sucesso. Deve ser uma combinação de indicadores de bits da NumberStyles enumeração.
Dependendo do valor de style, o s parâmetro pode incluir os seguintes elementos:
[ws][$][signo] dígitos[.fractional_digits][E[signo]exponential_digits][ws]
Se style inclui NumberStyles.AllowHexSpecifier, o s parâmetro pode conter os seguintes elementos:
[ws]hexdigits[ws]
Os elementos entre parênteses retos ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.
| Elemento | Descrição |
|---|---|
| ws | Espaço em branco opcional. O espaço em branco pode aparecer no início de s se style inclui a NumberStyles.AllowLeadingWhite bandeira, e pode aparecer no final de s se o estilo inclui a NumberStyles.AllowTrailingWhite bandeira. |
| $ | Um símbolo monetário específico de cada cultura. A sua posição na corda é definida pela NumberFormatInfo.CurrencyPositivePattern propriedade da cultura atual. O símbolo monetário da cultura atual pode aparecer se sstyle incluir a NumberStyles.AllowCurrencySymbol bandeira. |
| assinar | Um sinal opcional. O sinal pode aparecer no início de s se inclui a style bandeira, e pode aparecer no final de NumberStyles.AllowLeadingSign se s inclui a styleNumberStyles.AllowTrailingSign bandeira. Parênteses podem ser usados s para indicar um valor negativo se style incluir a NumberStyles.AllowParentheses bandeira. |
| dígitos | Uma sequência de dígitos de 0 a 9. |
| . | Um símbolo de ponto decimal específico para cada cultura. O símbolo de ponto decimal da cultura atual pode aparecer em s se style incluir a NumberStyles.AllowDecimalPoint bandeira. |
| fractional_digits | Uma ou mais ocorrências do dígito 0-9 se style incluir a NumberStyles.AllowExponent bandeira, ou uma ou mais ocorrências do dígito 0 se não incluir. Os dígitos fracionários só podem aparecer se sstyle incluir a NumberStyles.AllowDecimalPoint bandeira. |
| E | O carácter "e" ou "E", que indica que o valor é representado em notação exponencial (científica). O s parâmetro pode representar um número em notação exponencial se style incluir a NumberStyles.AllowExponent bandeira. |
| exponential_digits | Uma ou mais ocorrências do dígito 0-9. O s parâmetro pode representar um número em notação exponencial se style incluir a NumberStyles.AllowExponent bandeira. |
| Hexdigits | Uma sequência de dígitos hexadecimais de 0 a f, ou de 0 a F. |
Note
Quaisquer caracteres NUL terminantes (U+0000) em s são ignorados pela operação de análise, independentemente do valor do style argumento.
Uma cadeia apenas com dígitos decimais (que corresponde ao NumberStyles.None estilo) faz sempre análise com sucesso. A maioria dos membros restantes NumberStyles controla elementos que podem estar presentes, mas não são obrigados a estar, na cadeia de entrada. A tabela seguinte indica como os membros individuais NumberStyles afetam os elementos que podem estar presentes em s.
| Valores de NumberStyles não compostos | Elementos permitidos em s além dos dígitos |
|---|---|
| NumberStyles.None | Apenas dígitos decimais. |
| NumberStyles.AllowDecimalPoint | A vírgula decimal (.) e fractional_digits elementos. No entanto, se style não incluir a NumberStyles.AllowExponent bandeira, fractional_digits deve consistir apenas de um ou mais dígitos 0; caso contrário, um OverflowException é lançado. |
| NumberStyles.AllowExponent | O carácter "e" ou "E", que indica notação exponencial, juntamente com exponential_digits. |
| NumberStyles.AllowLeadingWhite | O elemento ws no início de s. |
| NumberStyles.AllowTrailingWhite | O elemento ws no final de s. |
| NumberStyles.AllowLeadingSign | Um sinal positivo antes dos dígitos. |
| NumberStyles.AllowTrailingSign | Um sinal positivo após os dígitos. |
| NumberStyles.AllowParentheses | O elemento do signo na forma de parênteses que envolvem o valor numérico. |
| NumberStyles.AllowThousands | O elemento separador de grupo (,). Embora o separador de grupo possa aparecer em s, deve ser precedido apenas por um ou mais dígitos 0. |
| NumberStyles.AllowCurrencySymbol | O elemento da moeda ($). |
Se a NumberStyles.AllowHexSpecifier bandeira for usada, s deve ser um valor hexadecimal. Os dígitos hexadecimais válidos são 0-9, a-f e A-F. Um prefixo como "0x" não é suportado e faz com que a operação de análise falhe. As únicas outras bandeiras que podem ser combinadas incluídas em style são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A NumberStyles enumeração inclui um estilo numérico composto, NumberStyles.HexNumber, que inclui ambas as bandeiras de espaço em branco.)
Note
Se o s parâmetro for a representação em cadeia de um número hexadecimal, não pode ser precedido por nenhuma decoração (como 0x ou &h) que o diferencie de um número hexadecimal. Isto faz com que a operação de análise sintética lance uma exceção.
Se s representa um número hexadecimal, o Parse(String, NumberStyles) método interpreta o bit de ordem superior do byte como um bit de sinal.
O s parâmetro é analisado utilizando a informação de formatação num NumberFormatInfo objeto que é inicializado para a cultura do sistema atual. Para usar a informação de formatação de outra cultura, chame a Parse(String, NumberStyles, IFormatProvider) sobrecarga.
Ver também
Aplica-se a
Parse(String, IFormatProvider)
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
Importante
Esta API não está em conformidade com CLS.
- Alternativa em conformidade com CLS
- System.Int16.Parse(String)
Converte a representação da cadeia de um número num formato específico de cultura para o seu equivalente inteiro com sinal de 8 bits.
public:
static System::SByte Parse(System::String ^ s, IFormatProvider ^ provider);
public:
static System::SByte Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<System::SByte>::Parse;
[System.CLSCompliant(false)]
public static sbyte Parse(string s, IFormatProvider provider);
public static sbyte Parse(string s, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static sbyte Parse(string s, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * IFormatProvider -> sbyte
static member Parse : string * IFormatProvider -> sbyte
Public Shared Function Parse (s As String, provider As IFormatProvider) As SByte
Parâmetros
- s
- String
Uma cadeia que representa um número a converter. A corda é interpretada usando o Integer estilo.
- provider
- IFormatProvider
Um objeto que fornece informação de formatação específica de cultura sobre s. Se provider for null, usa-se a cultura atual do fio.
Devoluções
Um inteiro com sinal de 8 bits que é equivalente ao número especificado em s.
Implementações
- Atributos
Exceções
s é null.
s não está no formato correto.
s representa um número inferior a SByte.MinValue ou superior a SByte.MaxValue.
Exemplos
O exemplo seguinte define um objeto personalizado NumberFormatInfo que define o tilde (~) como o sinal negativo. Depois, analisa várias cadeias numéricas usando este objeto personalizado NumberFormatInfo , bem como um CultureInfo objeto que representa a cultura invariante.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
NumberFormatInfo nf = new NumberFormatInfo();
nf.NegativeSign = "~";
string[] values = { "-103", "+12", "~16", " 1", "~255" };
IFormatProvider[] providers = { nf, CultureInfo.InvariantCulture };
foreach (IFormatProvider provider in providers)
{
Console.WriteLine("Conversions using {0}:", ((object) provider).GetType().Name);
foreach (string value in values)
{
try {
Console.WriteLine(" Converted '{0}' to {1}.",
value, SByte.Parse(value, provider));
}
catch (FormatException) {
Console.WriteLine(" Unable to parse '{0}'.", value);
}
catch (OverflowException) {
Console.WriteLine(" '{0}' is out of range of the SByte type.", value);
}
}
}
}
}
// The example displays the following output:
// Conversions using NumberFormatInfo:
// Unable to parse '-103'.
// Converted '+12' to 12.
// Converted '~16' to -16.
// Converted ' 1' to 1.
// '~255' is out of range of the SByte type.
// Conversions using CultureInfo:
// Converted '-103' to -103.
// Converted '+12' to 12.
// Unable to parse '~16'.
// Converted ' 1' to 1.
// Unable to parse '~255'.
open System
open System.Globalization
let nf = NumberFormatInfo()
nf.NegativeSign <- "~"
let values = [| "-103"; "+12"; "~16"; " 1"; "~255" |]
let providers: IFormatProvider[] = [| nf; CultureInfo.InvariantCulture |]
for provider in providers do
printfn $"Conversions using {(box provider).GetType().Name}:"
for value in values do
try
printfn $" Converted '{value}' to {SByte.Parse(value, provider)}."
with
| :? FormatException ->
printfn $" Unable to parse '{value}'."
| :? OverflowException ->
printfn $" '{value}' is out of range of the SByte type."
// The example displays the following output:
// Conversions using NumberFormatInfo:
// Unable to parse '-103'.
// Converted '+12' to 12.
// Converted '~16' to -16.
// Converted ' 1' to 1.
// '~255' is out of range of the SByte type.
// Conversions using CultureInfo:
// Converted '-103' to -103.
// Converted '+12' to 12.
// Unable to parse '~16'.
// Converted ' 1' to 1.
// Unable to parse '~255'.
Imports System.Globalization
Module Example
Public Sub Main()
Dim nf As New NumberFormatInfo()
nf.NegativeSign = "~"
Dim values() As String = { "-103", "+12", "~16", " 1", "~255" }
Dim providers() As IFormatProvider = { nf, CultureInfo.InvariantCulture }
For Each provider As IFormatProvider In providers
Console.WriteLine("Conversions using {0}:", CObj(provider).GetType().Name)
For Each value As String In values
Try
Console.WriteLine(" Converted '{0}' to {1}.", _
value, SByte.Parse(value, provider))
Catch e As FormatException
Console.WriteLine(" Unable to parse '{0}'.", value)
Catch e As OverflowException
Console.WriteLine(" '{0}' is out of range of the SByte type.", value)
End Try
Next
Next
End Sub
End Module
' The example displays '
' Conversions using NumberFormatInfo:
' Unable to parse '-103'.
' Converted '+12' to 12.
' Converted '~16' to -16.
' Converted ' 1' to 1.
' '~255' is out of range of the SByte type.
' Conversions using CultureInfo:
' Converted '-103' to -103.
' Converted '+12' to 12.
' Unable to parse '~16'.
' Converted ' 1' to 1.
' Unable to parse '~255'.
Observações
O s parâmetro contém um número da forma:
[ws][sinal]dígitos[ws]
Os elementos entre parênteses retos ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.
| Elemento | Descrição |
|---|---|
| ws | Espaço em branco opcional. |
| assinar | Um sinal opcional. |
| dígitos | Uma sequência de dígitos que varia de 0 a 9. |
O s parâmetro é interpretado usando o Integer estilo. Para além dos dígitos decimais do valor do byte, apenas espaços iniciais e finais com sinal inicial são permitidos. Para definir explicitamente os elementos de estilo com a informação de formatação específica da cultura que pode estar presente em s, use o Parse(String, NumberStyles, IFormatProvider) método.
O provider parâmetro é uma IFormatProvider implementação cujo GetFormat método devolve um NumberFormatInfo objeto que fornece informação específica de cultura sobre o formato de s. Existem três formas de usar o provider parâmetro para fornecer informação de formatação personalizada à operação de análise sintática:
Podes passar o objeto real NumberFormatInfo que fornece a informação de formatação. (A sua implementação de GetFormat simplesmente devolve-se a si própria.)
Pode passar um CultureInfo objeto que especifique a cultura cuja formatação deve ser usada. A sua NumberFormat propriedade fornece informação de formatação.
Pode passar uma implementação personalizada IFormatProvider . O seu GetFormat método deve instanciar e devolver o NumberFormatInfo objeto que fornece a informação de formatação.
Se provider for null, o NumberFormatInfo objeto para a cultura atual é usado.
Ver também
Aplica-se a
Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
Analisa um intervalo de caracteres UTF-8 num valor.
public static sbyte Parse(ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> sbyte
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As SByte
Parâmetros
- utf8Text
- ReadOnlySpan<Byte>
A extensão de caracteres UTF-8 para analisar.
- style
- NumberStyles
Uma combinação bit a bit de estilos numéricos que pode estar presente em utf8Text.
- provider
- IFormatProvider
Um objeto que fornece informação de formatação específica da cultura sobre utf8Text.
Devoluções
O resultado da análise sintática utf8Text.
Implementações
Aplica-se a
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
Importante
Esta API não está em conformidade com CLS.
Converte a representação span de um número que está num estilo especificado e formato específico de cultura para o seu equivalente com sinal de 8 bits.
public static sbyte Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
[System.CLSCompliant(false)]
public static sbyte Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
[System.CLSCompliant(false)]
public static sbyte Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> sbyte
[<System.CLSCompliant(false)>]
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> sbyte
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As SByte
Parâmetros
- s
- ReadOnlySpan<Char>
Um espaço que contém os caracteres que representam o número a converter. O espaço é interpretado usando o estilo especificado por style.
- style
- NumberStyles
Uma combinação bit a bit dos valores de enumeração que indica os elementos de estilo que podem estar presentes em s. Um valor típico a especificar é Integer.
- provider
- IFormatProvider
Um objeto que fornece informação de formatação específica de cultura sobre s. Se provider for null, usa-se a cultura atual do fio.
Devoluções
Um valor de byte assinado de 8 bits que é equivalente ao número especificado no s parâmetro.
Implementações
- Atributos
Aplica-se a
Parse(String, NumberStyles, IFormatProvider)
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
- Origem:
- SByte.cs
Importante
Esta API não está em conformidade com CLS.
- Alternativa em conformidade com CLS
- System.Int16.Parse(String, NumberStyles, IFormatProvider)
Converte a representação da cadeia de um número que está num estilo especificado e formato específico de cultura para o seu equivalente com sinal de 8 bits.
public:
static System::SByte Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
static System::SByte Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<System::SByte>::Parse;
[System.CLSCompliant(false)]
public static sbyte Parse(string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static sbyte Parse(string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static sbyte Parse(string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> sbyte
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> sbyte
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As SByte
Parâmetros
- s
- String
Uma cadeia que contém o número a converter. A cadeia é interpretada usando o estilo especificado por style.
- style
- NumberStyles
Uma combinação bit a bit dos valores de enumeração que indica os elementos de estilo que podem estar presentes em s. Um valor típico a especificar é Integer.
- provider
- IFormatProvider
Um objeto que fornece informação de formatação específica de cultura sobre s. Se provider for null, usa-se a cultura atual do fio.
Devoluções
Um valor de byte assinado de 8 bits que é equivalente ao número especificado no s parâmetro.
Implementações
- Atributos
Exceções
style não é um NumberStyles valor.
-ou-
style não é uma combinação de AllowHexSpecifier e HexNumber.
s é null.
s não está num formato compatível com style.
s representa um número menor que SByte.MinValue ou maior que SByte.MaxValue.
-ou-
s inclui dígitos fracionados e não nulos.
Exemplos
O exemplo seguinte ilustra o uso do Parse(String, NumberStyles, IFormatProvider) método para converter várias representações de números em cadeia em valores inteiros com sinal.
using System;
using System.Globalization;
public class SByteConversion
{
NumberFormatInfo provider = NumberFormatInfo.CurrentInfo;
public static void Main()
{
string stringValue;
NumberStyles style;
stringValue = " 123 ";
style = NumberStyles.None;
CallParseOperation(stringValue, style);
stringValue = "000,000,123";
style = NumberStyles.Integer | NumberStyles.AllowThousands;
CallParseOperation(stringValue, style);
stringValue = "-100";
style = NumberStyles.AllowLeadingSign;
CallParseOperation(stringValue, style);
stringValue = "100-";
style = NumberStyles.AllowLeadingSign;
CallParseOperation(stringValue, style);
stringValue = "100-";
style = NumberStyles.AllowTrailingSign;
CallParseOperation(stringValue, style);
stringValue = "$100";
style = NumberStyles.AllowCurrencySymbol;
CallParseOperation(stringValue, style);
style = NumberStyles.Integer;
CallParseOperation(stringValue, style);
style = NumberStyles.AllowDecimalPoint;
CallParseOperation("100.0", style);
stringValue = "1e02";
style = NumberStyles.AllowExponent;
CallParseOperation(stringValue, style);
stringValue = "(100)";
style = NumberStyles.AllowParentheses;
CallParseOperation(stringValue, style);
}
private static void CallParseOperation(string stringValue,
NumberStyles style)
{
sbyte number;
if (stringValue == null)
Console.WriteLine("Cannot parse a null string...");
try
{
number = sbyte.Parse(stringValue, style);
Console.WriteLine("SByte.Parse('{0}', {1})) = {2}",
stringValue, style, number);
}
catch (FormatException)
{
Console.WriteLine("'{0}' and {1} throw a FormatException",
stringValue, style);
}
catch (OverflowException)
{
Console.WriteLine("'{0}' is outside the range of a signed byte",
stringValue);
}
}
}
// The example displays the following information to the console:
// ' 123 ' and None throw a FormatException
// SByte.Parse('000,000,123', Integer, AllowThousands)) = 123
// SByte.Parse('-100', AllowLeadingSign)) = -100
// '100-' and AllowLeadingSign throw a FormatException
// SByte.Parse('100-', AllowTrailingSign)) = -100
// SByte.Parse('$100', AllowCurrencySymbol)) = 100
// '$100' and Integer throw a FormatException
// SByte.Parse('100.0', AllowDecimalPoint)) = 100
// SByte.Parse('1e02', AllowExponent)) = 100
// SByte.Parse('(100)', AllowParentheses)) = -100
open System
open System.Globalization
let provider = NumberFormatInfo.CurrentInfo
let callParseOperation stringValue (style: NumberStyles) =
if stringValue = null then
printfn "Cannot parse a null string..."
else
try
let number = SByte.Parse(stringValue, style)
printfn $"SByte.Parse('{stringValue}', {style})) = {number}"
with
| :? FormatException ->
printfn $"'{stringValue}' and {style} throw a FormatException"
| :? OverflowException ->
printfn $"'{stringValue}' is outside the range of a signed byte"
[<EntryPoint>]
let main _ =
let stringValue = " 123 "
let style = NumberStyles.None
callParseOperation stringValue style
let stringValue = "000,000,123"
let style = NumberStyles.Integer ||| NumberStyles.AllowThousands
callParseOperation stringValue style
let stringValue = "-100"
let style = NumberStyles.AllowLeadingSign
callParseOperation stringValue style
let stringValue = "100-"
let style = NumberStyles.AllowLeadingSign
callParseOperation stringValue style
let stringValue = "100-"
let style = NumberStyles.AllowTrailingSign
callParseOperation stringValue style
let stringValue = "$100"
let style = NumberStyles.AllowCurrencySymbol
callParseOperation stringValue style
let style = NumberStyles.Integer
callParseOperation stringValue style
let style = NumberStyles.AllowDecimalPoint
callParseOperation "100.0" style
let stringValue = "1e02"
let style = NumberStyles.AllowExponent
callParseOperation stringValue style
let stringValue = "(100)"
let style = NumberStyles.AllowParentheses
callParseOperation stringValue style
0
// The example displays the following information to the console:
// ' 123 ' and None throw a FormatException
// SByte.Parse('000,000,123', Integer, AllowThousands)) = 123
// SByte.Parse('-100', AllowLeadingSign)) = -100
// '100-' and AllowLeadingSign throw a FormatException
// SByte.Parse('100-', AllowTrailingSign)) = -100
// SByte.Parse('$100', AllowCurrencySymbol)) = 100
// '$100' and Integer throw a FormatException
// SByte.Parse('100.0', AllowDecimalPoint)) = 100
// SByte.Parse('1e02', AllowExponent)) = 100
// SByte.Parse('(100)', AllowParentheses)) = -100
Imports System.Globalization
Module modMain
Public Sub Main()
Dim byteString As String
byteString = " 123"
ParseString(byteString, NumberStyles.None)
ParseString(byteString, NumberStyles.Integer)
byteString = "3A"
ParseString(byteString, NumberStyles.AllowHexSpecifier)
byteString = "21"
ParseString(byteString, NumberStyles.Integer)
ParseString(byteString, NumberStyles.AllowHexSpecifier)
byteString = "-22"
ParseString(byteString, NumberStyles.Integer)
ParseString(byteString, NumberStyles.AllowParentheses)
byteString = "(45)"
ParseString(byteString, NumberStyles.AllowParentheses)
byteString = "000,000,056"
ParseString(byteString, NumberStyles.Integer)
ParseString(byteString, NumberStyles.Integer Or NumberStyles.AllowThousands)
End Sub
Private Sub ParseString(value As String, style As NumberStyles)
Dim number As SByte
If value Is Nothing Then Console.WriteLine("Cannot parse a null string...")
Try
number = SByte.Parse(value, style, NumberFormatInfo.CurrentInfo)
Console.WriteLine("SByte.Parse('{0}', {1}) = {2}", value, style, number)
Catch e As FormatException
Console.WriteLine("'{0}' and {1} throw a FormatException", value, style)
Catch e As OverflowException
Console.WriteLine("'{0}' is outside the range of a signed byte",
value)
End Try
End Sub
End Module
' The example displays the following information to the console:
' ' 123' and None throw a FormatException
' SByte.Parse(" 123", Integer)) = 123
' SByte.Parse("3A", AllowHexSpecifier)) = 58
' SByte.Parse("21", Integer)) = 21
' SByte.Parse("21", AllowHexSpecifier)) = 33
' SByte.Parse("-22", Integer)) = -22
' '-22' and AllowParentheses throw a FormatException
' SByte.Parse("(45)", AllowParentheses)) = -45
' '000,000,056' and Integer throw a FormatException
' SByte.Parse("000,000,056", Integer, AllowThousands)) = 56
Observações
O style parâmetro define os elementos de estilo (como espaços em branco ou o símbolo de sinal positivo ou negativo) que são permitidos no s parâmetro para que a operação de análise sintética tenha sucesso. Deve ser uma combinação de indicadores de bits da NumberStyles enumeração.
Dependendo do valor de style, o s parâmetro pode incluir os seguintes elementos:
[ws][$][signo] dígitos[.fractional_digits][E[signo]exponential_digits][ws]
Se style inclui AllowHexSpecifier, o s parâmetro pode incluir os seguintes elementos:
[ws]hexdigits[ws]
Os elementos entre parênteses retos ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.
| Elemento | Descrição |
|---|---|
| ws | Espaço em branco opcional. O espaço em branco pode aparecer no início de s se style inclui a NumberStyles.AllowLeadingWhite bandeira, e pode aparecer no final de s se style inclui a NumberStyles.AllowTrailingWhite bandeira. |
| $ | Um símbolo monetário específico de cada cultura. A sua posição na corda é definida pela NumberFormatInfo.CurrencyPositivePattern propriedade da cultura atual. O símbolo monetário da cultura atual pode aparecer se sstyle incluir a NumberStyles.AllowCurrencySymbol bandeira. |
| assinar | Um sinal opcional. O sinal pode aparecer no início de s se inclui a style bandeira, e pode aparecer no final de NumberStyles.AllowLeadingSign se s inclui a styleNumberStyles.AllowTrailingSign bandeira. Parênteses podem ser usados s para indicar um valor negativo se style incluir a NumberStyles.AllowParentheses bandeira. |
| dígitos | Uma sequência de dígitos de 0 a 9. |
| . | Um símbolo de ponto decimal específico para cada cultura. O símbolo de ponto decimal da cultura atual pode aparecer em s se style incluir a NumberStyles.AllowDecimalPoint bandeira. |
| fractional_digits | Uma ou mais ocorrências do dígito 0-9 se style incluir a NumberStyles.AllowExponent bandeira, ou uma ou mais ocorrências do dígito 0 se não incluir. Os dígitos fracionários só podem aparecer se sstyle incluir a NumberStyles.AllowDecimalPoint bandeira. |
| E | O carácter "e" ou "E", que indica que o valor é representado em notação exponencial (científica). O s parâmetro pode representar um número em notação exponencial se style incluir a NumberStyles.AllowExponent bandeira. |
| exponential_digits | Uma sequência de dígitos de 0 a 9. O s parâmetro pode representar um número em notação exponencial se style incluir a NumberStyles.AllowExponent bandeira. |
| Hexdigits | Uma sequência de dígitos hexadecimais de 0 a f, ou de 0 a F. |
Note
Quaisquer caracteres NUL terminantes (U+0000) em s são ignorados pela operação de análise, independentemente do valor do style argumento.
Uma cadeia apenas com dígitos decimais (que corresponde ao NumberStyles.None estilo) faz sempre análise com sucesso. A maioria dos membros restantes NumberStyles controla elementos que podem estar presentes, mas que não são obrigados a estar presentes, nesta cadeia de entrada. A tabela seguinte indica como os membros individuais NumberStyles afetam os elementos que podem estar presentes em s.
Valores não compostos NumberStyles |
Elementos permitidos s além dos dígitos |
|---|---|
| NumberStyles.None | Apenas dígitos decimais. |
| NumberStyles.AllowDecimalPoint | A vírgula decimal (.) e fractional_digits elementos. No entanto, se o estilo não incluir a NumberStyles.AllowExponent bandeira, fractional_digits deve consistir apenas de um ou mais dígitos 0; caso contrário, um OverflowException é lançado. |
| NumberStyles.AllowExponent | O carácter "e" ou "E", que indica notação exponencial, juntamente com exponential_digits. |
| NumberStyles.AllowLeadingWhite | O elemento ws no início de s. |
| NumberStyles.AllowTrailingWhite | O elemento ws no final de s. |
| NumberStyles.AllowLeadingSign | Um sinal positivo antes dos dígitos. |
| NumberStyles.AllowTrailingSign | Um sinal positivo após os dígitos. |
| NumberStyles.AllowParentheses | Parênteses entre dígitos antes e depois para indicar um valor negativo. |
| NumberStyles.AllowThousands | O elemento separador de grupo (,). Embora o separador de grupo possa aparecer em s, deve ser precedido apenas por um ou mais dígitos 0. |
| NumberStyles.AllowCurrencySymbol | O elemento da moeda ($). |
Se a NumberStyles.AllowHexSpecifier bandeira for usada, s deve ser um valor hexadecimal. Os dígitos hexadecimais válidos são 0-9, a-f e A-F. As únicas outras bandeiras que podem ser combinadas com ela são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A NumberStyles enumeração inclui um estilo numérico composto, NumberStyles.HexNumber, que inclui ambas as bandeiras de espaço em branco.)
Note
Se o s parâmetro for a representação em cadeia de um número hexadecimal, não pode ser precedido por nenhuma decoração (como 0x ou &h) que o diferencie de um número hexadecimal. Isto faz com que a operação de análise sintética lance uma exceção.
Se s representa um número hexadecimal, o Parse(String, NumberStyles) método interpreta o bit de ordem superior do byte como um bit de sinal.
O provider parâmetro é uma IFormatProvider implementação cujo GetFormat método devolve um NumberFormatInfo objeto que fornece informação específica de cultura sobre o formato de s. Existem três formas de usar o provider parâmetro para fornecer informação de formatação personalizada à operação de análise sintática:
Podes passar o objeto real NumberFormatInfo que fornece a informação de formatação. (A sua implementação de GetFormat simplesmente devolve-se a si própria.)
Pode passar um CultureInfo objeto que especifique a cultura cuja formatação deve ser usada. A sua NumberFormat propriedade fornece informação de formatação.
Pode passar uma implementação personalizada IFormatProvider . O seu GetFormat método deve instanciar e devolver o NumberFormatInfo objeto que fornece a informação de formatação.
Se provider for null, o NumberFormatInfo objeto para a cultura atual é usado.