UInt16.Parse Método
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Converte a representação de cadeia de caracteres de um número em seu equivalente inteiro sem sinal de 16 bits.
Sobrecargas
| Nome | Description |
|---|---|
| Parse(String, NumberStyles, IFormatProvider) |
Converte a representação de cadeia de caracteres de um número em um formato específico de cultura e estilo especificado em seu inteiro sem sinal de 16 bits equivalente. |
| Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) |
Converte a representação de intervalo de um número em um formato específico de cultura e estilo especificado em seu inteiro sem sinal de 16 bits equivalente. |
| Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider) |
Analisa um intervalo de caracteres UTF-8 em um valor. |
| Parse(String, IFormatProvider) |
Converte a representação de cadeia de caracteres de um número em um formato específico à cultura especificado em seu inteiro sem sinal de 16 bits equivalente. |
| Parse(String, NumberStyles) |
Converte a representação de cadeia de caracteres de um número em um estilo especificado em seu inteiro sem sinal de 16 bits equivalente. Esse método não é compatível com CLS. A alternativa compatível com CLS é Parse(String, NumberStyles). |
| Parse(ReadOnlySpan<Char>, IFormatProvider) |
Analisa um intervalo de caracteres em um valor. |
| Parse(ReadOnlySpan<Byte>, IFormatProvider) |
Analisa um intervalo de caracteres UTF-8 em um valor. |
| Parse(String) |
Converte a representação de cadeia de caracteres de um número em seu equivalente inteiro sem sinal de 16 bits. |
Parse(String, NumberStyles, IFormatProvider)
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
Importante
Esta API não está em conformidade com CLS.
- Alternativa em conformidade com CLS
- System.Int32.Parse(String)
Converte a representação de cadeia de caracteres de um número em um formato específico de cultura e estilo especificado em seu inteiro sem sinal de 16 bits equivalente.
public:
static System::UInt16 Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
static System::UInt16 Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<System::UInt16>::Parse;
[System.CLSCompliant(false)]
public static ushort Parse(string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static ushort Parse(string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static ushort Parse(string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> uint16
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> uint16
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As UShort
Parâmetros
- s
- String
Uma cadeia de caracteres que representa o número a ser convertido. A cadeia de caracteres é interpretada usando o estilo especificado pelo style parâmetro.
- style
- NumberStyles
Uma combinação bit a bit de valores de enumeração que indicam os elementos de estilo que podem estar presentes em s. Um valor típico a ser especificado é Integer.
- provider
- IFormatProvider
Um objeto que fornece informações de formatação específicas da cultura sobre s.
Retornos
Um inteiro sem sinal de 16 bits equivalente ao número especificado em s.
Implementações
- Atributos
Exceções
s é null.
style não é um NumberStyles valor.
-ou-
style não é uma combinação de AllowHexSpecifier valores e valores HexNumber .
s não está em um formato compatível com style.
s representa um número menor que UInt16.MinValue ou maior que UInt16.MaxValue.
-ou-
s inclui dígitos não zero e fracionários.
Exemplos
O exemplo a seguir usa o Parse(String, NumberStyles, IFormatProvider) método para converter várias representações de cadeia de caracteres de números em valores inteiros sem sinal de 16 bits.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] cultureNames = { "en-US", "fr-FR" };
NumberStyles[] styles= { NumberStyles.Integer,
NumberStyles.Integer | NumberStyles.AllowDecimalPoint };
string[] values = { "1702", "+1702.0", "+1702,0", "-1032.00",
"-1032,00", "1045.1", "1045,1" };
// Parse strings using each culture
foreach (string cultureName in cultureNames)
{
CultureInfo ci = new CultureInfo(cultureName);
Console.WriteLine("Parsing strings using the {0} culture",
ci.DisplayName);
// Use each style.
foreach (NumberStyles style in styles)
{
Console.WriteLine(" Style: {0}", style.ToString());
// Parse each numeric string.
foreach (string value in values)
{
try {
Console.WriteLine(" Converted '{0}' to {1}.", value,
UInt16.Parse(value, style, ci));
}
catch (FormatException) {
Console.WriteLine(" Unable to parse '{0}'.", value);
}
catch (OverflowException) {
Console.WriteLine(" '{0}' is out of range of the UInt16 type.",
value);
}
}
}
}
}
}
// The example displays the following output:
// Parsing strings using the English (United States) culture
// Style: Integer
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Unable to parse '+1702,0'.
// Unable to parse '-1032.00'.
// Unable to parse '-1032,00'.
// Unable to parse '1045.1'.
// Unable to parse '1045,1'.
// Style: Integer, AllowDecimalPoint
// Converted '1702' to 1702.
// Converted '+1702.0' to 1702.
// Unable to parse '+1702,0'.
// '-1032.00' is out of range of the UInt16 type.
// Unable to parse '-1032,00'.
// '1045.1' is out of range of the UInt16 type.
// Unable to parse '1045,1'.
// Parsing strings using the French (France) culture
// Style: Integer
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Unable to parse '+1702,0'.
// Unable to parse '-1032.00'.
// Unable to parse '-1032,00'.
// Unable to parse '1045.1'.
// Unable to parse '1045,1'.
// Style: Integer, AllowDecimalPoint
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Converted '+1702,0' to 1702.
// Unable to parse '-1032.00'.
// '-1032,00' is out of range of the UInt16 type.
// Unable to parse '1045.1'.
// '1045,1' is out of range of the UInt16 type.
open System
open System.Globalization
let cultureNames = [| "en-US"; "fr-FR" |]
let styles =
[| NumberStyles.Integer; NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint |]
let values =
[| "1702"; "+1702.0"; "+1702,0"; "-1032.00"; "-1032,00"; "1045.1"; "1045,1" |]
// Parse strings using each culture
for cultureName in cultureNames do
let ci = CultureInfo cultureName
printfn $"Parsing strings using the {ci.DisplayName} culture"
// Use each style.
for style in styles do
printfn $" Style: {style}"
// Parse each numeric string.
for value in values do
try
printfn $" Converted '{value}' to {UInt16.Parse(value, style, ci)}."
with
| :? FormatException ->
printfn $" Unable to parse '{value}'."
| :? OverflowException ->
printfn $" '{value}' is out of range of the UInt16 type."
// The example displays the following output:
// Parsing strings using the English (United States) culture
// Style: Integer
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Unable to parse '+1702,0'.
// Unable to parse '-1032.00'.
// Unable to parse '-1032,00'.
// Unable to parse '1045.1'.
// Unable to parse '1045,1'.
// Style: Integer, AllowDecimalPoint
// Converted '1702' to 1702.
// Converted '+1702.0' to 1702.
// Unable to parse '+1702,0'.
// '-1032.00' is out of range of the UInt16 type.
// Unable to parse '-1032,00'.
// '1045.1' is out of range of the UInt16 type.
// Unable to parse '1045,1'.
// Parsing strings using the French (France) culture
// Style: Integer
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Unable to parse '+1702,0'.
// Unable to parse '-1032.00'.
// Unable to parse '-1032,00'.
// Unable to parse '1045.1'.
// Unable to parse '1045,1'.
// Style: Integer, AllowDecimalPoint
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Converted '+1702,0' to 1702.
// Unable to parse '-1032.00'.
// '-1032,00' is out of range of the UInt16 type.
// Unable to parse '1045.1'.
// '1045,1' is out of range of the UInt16 type.
Imports System.Globalization
Module Example
Public Sub Main()
Dim cultureNames() As String = { "en-US", "fr-FR" }
Dim styles() As NumberStyles = { NumberStyles.Integer, _
NumberStyles.Integer Or NumberStyles.AllowDecimalPoint }
Dim values() As String = { "1702", "+1702.0", "+1702,0", "-1032.00", _
"-1032,00", "1045.1", "1045,1" }
' Parse strings using each culture
For Each cultureName As String In cultureNames
Dim ci As New CultureInfo(cultureName)
Console.WriteLine("Parsing strings using the {0} culture", ci.DisplayName)
' Use each style.
For Each style As NumberStyles In styles
Console.WriteLine(" Style: {0}", style.ToString())
' Parse each numeric string.
For Each value As String In values
Try
Console.WriteLine(" Converted '{0}' to {1}.", value, _
UInt16.Parse(value, style, ci))
Catch e As FormatException
Console.WriteLine(" Unable to parse '{0}'.", value)
Catch e As OverflowException
Console.WriteLine(" '{0}' is out of range of the UInt16 type.", _
value)
End Try
Next
Next
Next
End Sub
End Module
' The example displays the following output:
' Parsing strings using the English (United States) culture
' Style: Integer
' Converted '1702' to 1702.
' Unable to parse '+1702.0'.
' Unable to parse '+1702,0'.
' Unable to parse '-1032.00'.
' Unable to parse '-1032,00'.
' Unable to parse '1045.1'.
' Unable to parse '1045,1'.
' Style: Integer, AllowDecimalPoint
' Converted '1702' to 1702.
' Converted '+1702.0' to 1702.
' Unable to parse '+1702,0'.
' '-1032.00' is out of range of the UInt16 type.
' Unable to parse '-1032,00'.
' '1045.1' is out of range of the UInt16 type.
' Unable to parse '1045,1'.
' Parsing strings using the French (France) culture
' Style: Integer
' Converted '1702' to 1702.
' Unable to parse '+1702.0'.
' Unable to parse '+1702,0'.
' Unable to parse '-1032.00'.
' Unable to parse '-1032,00'.
' Unable to parse '1045.1'.
' Unable to parse '1045,1'.
' Style: Integer, AllowDecimalPoint
' Converted '1702' to 1702.
' Unable to parse '+1702.0'.
' Converted '+1702,0' to 1702.
' Unable to parse '-1032.00'.
' '-1032,00' is out of range of the UInt16 type.
' Unable to parse '1045.1'.
' '1045,1' is out of range of the UInt16 type.
Comentários
O style parâmetro define os elementos de estilo (como espaço 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 seja bem-sucedida. Deve ser uma combinação de sinalizadores de bits da NumberStyles enumeração.
Dependendo do valor de style, o s parâmetro pode incluir os seguintes elementos:
[ws][$][sign]digits[.fractional_digits][E[sign]exponential_digits][ws]
Elementos em colchetes ([ e ]) são opcionais. Se style incluir NumberStyles.AllowHexSpecifier, o s parâmetro poderá incluir os seguintes elementos:
[ws]hexdigits[ws]
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 incluir o NumberStyles.AllowLeadingWhite sinalizador e pode aparecer no final de s se style incluir o NumberStyles.AllowTrailingWhitestyle sinalizador. |
| $ | Um símbolo de moeda específico à cultura. Sua posição na cadeia de caracteres é definida pela CurrencyPositivePattern propriedade do NumberFormatInfo objeto que é retornada pelo GetFormat método do provider parâmetro. O símbolo de moeda poderá aparecer s se style incluir o NumberStyles.AllowCurrencySymbol sinalizador. |
| assinar | Um sinal opcional. (O método lança um OverflowException se s inclui um sinal negativo e representa um número diferente de zero.) O sinal pode aparecer no início de s se incluir o NumberStyles.AllowLeadingSign sinalizador e pode aparecer no final de s se style incluir o NumberStyles.AllowTrailingSignstyle sinalizador. Parênteses podem ser usados s para indicar um valor negativo se style incluir o NumberStyles.AllowParentheses sinalizador. |
| Dígitos | Uma sequência de dígitos de 0 a 9. |
| . | Um símbolo de ponto decimal específico da cultura. O símbolo de ponto decimal da cultura atual poderá aparecer s se style incluir o NumberStyles.AllowDecimalPoint sinalizador. |
| Fractional_digits | Uma ou mais ocorrências do dígito 0-9 se style incluir o NumberStyles.AllowExponent sinalizador ou uma ou mais ocorrências do dígito 0 se não o fizer. Dígitos fracionários só poderão aparecer s se style incluir o NumberStyles.AllowDecimalPoint sinalizador. |
| E | O caractere "e" ou "E", que indica que o valor é representado na notação exponencial (científica). O s parâmetro pode representar um número na notação exponencial se style incluir o NumberStyles.AllowExponent sinalizador. |
| exponential_digits | Uma sequência de dígitos de 0 a 9. O s parâmetro pode representar um número na notação exponencial se style incluir o NumberStyles.AllowExponent sinalizador. |
| hexdigits | Uma sequência de dígitos hexadecimal de 0 a f ou 0 a F. |
Nota
Todos os caracteres s NUL de terminação (U+0000) são ignorados pela operação de análise, independentemente do valor do style argumento.
Uma cadeia de caracteres somente com dígitos decimais (que corresponde ao NumberStyles.None estilo) sempre é analisada com êxito. A maioria dos elementos de controle de membros restantes NumberStyles que podem estar presentes, mas não precisam estar presentes, nesta cadeia de caracteres de entrada. A tabela a seguir 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 de dígitos |
|---|---|
| NumberStyles.None | Somente dígitos decimais. |
| NumberStyles.AllowDecimalPoint | O ponto decimal (.) e os elementos fractional_digits. No entanto, se o estilo não incluir o NumberStyles.AllowExponent sinalizador, fractional_digits deverá consistir em apenas um ou mais 0 dígitos; caso contrário, um OverflowException será gerado. |
| NumberStyles.AllowExponent | O caractere "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 antes dos dígitos. |
| NumberStyles.AllowTrailingSign | Um sinal após dígitos. |
| NumberStyles.AllowParentheses | Parênteses antes e depois dos dígitos para indicar um valor negativo. |
| NumberStyles.AllowThousands | O elemento separador de grupo (,). |
| NumberStyles.AllowCurrencySymbol | O elemento currency ($). |
Se o NumberStyles.AllowHexSpecifier sinalizador for usado, s deverá ser um valor hexadecimal. Os dígitos hexadecimal válidos são de 0 a 9, a a f e A a F. Não há suporte para um prefixo, como "0x", e faz com que a operação de análise falhe. Os únicos outros sinalizadores que podem ser combinados são NumberStyles.AllowHexSpecifierNumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A NumberStyles enumeração inclui um estilo de número composto, NumberStyles.HexNumberque inclui sinalizadores de espaço em branco.)
Nota
Se o s parâmetro for a representação de cadeia de caracteres de um número hexadecimal, ele não poderá ser precedido por qualquer decoração (como 0x ou &h) que a diferencie como um número hexadecimal. Isso faz com que a operação de análise gere uma exceção.
O provider parâmetro é uma implementação IFormatProvider cujo GetFormat método retorna um NumberFormatInfo objeto que fornece informações específicas da cultura sobre o formato de s. Há três maneiras de usar o provider parâmetro para fornecer informações de formatação personalizadas para a operação de análise:
Você pode passar o objeto real NumberFormatInfo que fornece informações de formatação. (Sua implementação de GetFormat simplesmente retorna a si mesma.)
Você pode passar um CultureInfo objeto que especifica a cultura cuja formatação deve ser usada. Sua NumberFormat propriedade fornece informações de formatação.
Você pode passar uma implementação personalizada IFormatProvider . Seu GetFormat método deve instanciar e retornar o NumberFormatInfo objeto que fornece informações de formatação.
Se provider for null, o NumberFormatInfo objeto para a cultura atual será usado.
Confira também
Aplica-se a
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
Importante
Esta API não está em conformidade com CLS.
Converte a representação de intervalo de um número em um formato específico de cultura e estilo especificado em seu inteiro sem sinal de 16 bits equivalente.
public static ushort Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
[System.CLSCompliant(false)]
public static ushort Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
[System.CLSCompliant(false)]
public static ushort Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> uint16
[<System.CLSCompliant(false)>]
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> uint16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As UShort
Parâmetros
- s
- ReadOnlySpan<Char>
Um intervalo que contém os caracteres que representam o número a ser convertido. O intervalo é interpretado usando o estilo especificado pelo style parâmetro.
- style
- NumberStyles
Uma combinação bit a bit de valores de enumeração que indicam os elementos de estilo que podem estar presentes em s. Um valor típico a ser especificado é Integer.
- provider
- IFormatProvider
Um objeto que fornece informações de formatação específicas da cultura sobre s.
Retornos
Um inteiro sem sinal de 16 bits equivalente ao número especificado em s.
Implementações
- Atributos
Aplica-se a
Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
Analisa um intervalo de caracteres UTF-8 em um valor.
public static ushort Parse(ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> uint16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As UShort
Parâmetros
- utf8Text
- ReadOnlySpan<Byte>
O intervalo de caracteres UTF-8 a serem analisados.
- style
- NumberStyles
Uma combinação bit a bit de estilos numéricos que podem estar presentes em utf8Text.
- provider
- IFormatProvider
Um objeto que fornece informações de formatação específicas da cultura sobre utf8Text.
Retornos
O resultado da análise utf8Text.
Implementações
Aplica-se a
Parse(String, IFormatProvider)
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
Importante
Esta API não está em conformidade com CLS.
- Alternativa em conformidade com CLS
- System.Int32.Parse(String)
Converte a representação de cadeia de caracteres de um número em um formato específico à cultura especificado em seu inteiro sem sinal de 16 bits equivalente.
public:
static System::UInt16 Parse(System::String ^ s, IFormatProvider ^ provider);
public:
static System::UInt16 Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<System::UInt16>::Parse;
[System.CLSCompliant(false)]
public static ushort Parse(string s, IFormatProvider provider);
public static ushort Parse(string s, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static ushort Parse(string s, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * IFormatProvider -> uint16
static member Parse : string * IFormatProvider -> uint16
Public Shared Function Parse (s As String, provider As IFormatProvider) As UShort
Parâmetros
- s
- String
Uma cadeia de caracteres que representa o número a ser convertido.
- provider
- IFormatProvider
Um objeto que fornece informações de formatação específicas da cultura sobre s.
Retornos
Um inteiro sem sinal de 16 bits 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 menor que UInt16.MinValue ou maior que UInt16.MaxValue.
Exemplos
O exemplo a seguir cria uma instância de uma cultura personalizada que usa dois sinais de adição (++) como sinal positivo. Em seguida, ele chama o Parse(String, IFormatProvider) método para analisar uma matriz de cadeias de caracteres usando CultureInfo objetos que representam essa cultura personalizada e a cultura invariável.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
// Define a custom culture that uses "++" as a positive sign.
CultureInfo ci = new CultureInfo("");
ci.NumberFormat.PositiveSign = "++";
// Create an array of cultures.
CultureInfo[] cultures = { ci, CultureInfo.InvariantCulture };
// Create an array of strings to parse.
string[] values = { "++1403", "-0", "+0", "+16034",
Int16.MinValue.ToString(), "14.0", "18012" };
// Parse the strings using each culture.
foreach (CultureInfo culture in cultures)
{
Console.WriteLine("Parsing with the '{0}' culture.", culture.Name);
foreach (string value in values)
{
try {
ushort number = UInt16.Parse(value, culture);
Console.WriteLine(" Converted '{0}' to {1}.", value, number);
}
catch (FormatException) {
Console.WriteLine(" The format of '{0}' is invalid.", value);
}
catch (OverflowException) {
Console.WriteLine(" '{0}' is outside the range of a UInt16 value.", value);
}
}
}
}
}
// The example displays the following output:
// Parsing with the culture.
// Converted '++1403' to 1403.
// Converted '-0' to 0.
// The format of '+0' is invalid.
// The format of '+16034' is invalid.
// '-32768' is outside the range of a UInt16 value.
// The format of '14.0' is invalid.
// Converted '18012' to 18012.
// Parsing with the '' culture.
// The format of '++1403' is invalid.
// Converted '-0' to 0.
// Converted '+0' to 0.
// Converted '+16034' to 16034.
// '-32768' is outside the range of a UInt16 value.
// The format of '14.0' is invalid.
// Converted '18012' to 18012.
open System
open System.Globalization
// Define a custom culture that uses "++" as a positive sign.
let ci = CultureInfo ""
ci.NumberFormat.PositiveSign <- "++"
// Create an array of cultures.
let cultures = [| ci; CultureInfo.InvariantCulture |]
// Create an array of strings to parse.
let values =
[| "++1403"; "-0"; "+0"; "+16034"
string Int16.MinValue; "14.0"; "18012" |]
// Parse the strings using each culture.
for culture in cultures do
printfn $"Parsing with the '{culture.Name}' culture."
for value in values do
try
let number = UInt16.Parse(value, culture)
printfn $" Converted '{value}' to {number}."
with
| :? FormatException ->
printfn $" The format of '{value}' is invalid."
| :? OverflowException ->
printfn $" '{value}' is outside the range of a UInt16 value."
// The example displays the following output:
// Parsing with the culture.
// Converted '++1403' to 1403.
// Converted '-0' to 0.
// The format of '+0' is invalid.
// The format of '+16034' is invalid.
// '-32768' is outside the range of a UInt16 value.
// The format of '14.0' is invalid.
// Converted '18012' to 18012.
// Parsing with the '' culture.
// The format of '++1403' is invalid.
// Converted '-0' to 0.
// Converted '+0' to 0.
// Converted '+16034' to 16034.
// '-32768' is outside the range of a UInt16 value.
// The format of '14.0' is invalid.
// Converted '18012' to 18012.
Imports System.Globalization
Module Example
Public Sub Main()
' Define a custom culture that uses "++" as a positive sign.
Dim ci As CultureInfo = New CultureInfo("")
ci.NumberFormat.PositiveSign = "++"
' Create an array of cultures.
Dim cultures() As CultureInfo = { ci, CultureInfo.InvariantCulture }
' Create an array of strings to parse.
Dim values() As String = { "++1403", "-0", "+0", "+16034", _
Int16.MinValue.ToString(), "14.0", "18012" }
' Parse the strings using each culture.
For Each culture As CultureInfo In cultures
Console.WriteLine("Parsing with the '{0}' culture.", culture.Name)
For Each value As String In values
Try
Dim number As UShort = UInt16.Parse(value, culture)
Console.WriteLine(" Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine(" The format of '{0}' is invalid.", value)
Catch e As OverflowException
Console.WriteLine(" '{0}' is outside the range of a UInt16 value.", value)
End Try
Next
Next
End Sub
End Module
' The example displays the following output:
' Parsing with the culture.
' Converted '++1403' to 1403.
' Converted '-0' to 0.
' The format of '+0' is invalid.
' The format of '+16034' is invalid.
' '-32768' is outside the range of a UInt16 value.
' The format of '14.0' is invalid.
' Converted '18012' to 18012.
' Parsing with the '' culture.
' The format of '++1403' is invalid.
' Converted '-0' to 0.
' Converted '+0' to 0.
' Converted '+16034' to 16034.
' '-32768' is outside the range of a UInt16 value.
' The format of '14.0' is invalid.
' Converted '18012' to 18012.
Comentários
O s parâmetro contém um número do formulário:
[ws][sign]digits[ws]
Itens em colchetes ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.
| Elemento | Descrição |
|---|---|
| Ws | Espaço em branco opcional. |
| sinal | Um sinal opcional ou um sinal negativo se s representar o valor zero. |
| Dígitos | Uma sequência de dígitos variando de 0 a 9. |
O parâmetro s é interpretado usando o NumberStyles.Integer estilo. Além dos dígitos decimais do valor de byte, somente espaços à esquerda e à direita, juntamente com um sinal à esquerda, são permitidos. (Se o sinal negativo estiver presente, s deverá representar um valor igual a zero ou o método gerará um OverflowException.) Para definir explicitamente os elementos de estilo junto com as informações de formatação específicas da cultura que podem estar presentes s, use o Parse(String, NumberStyles, IFormatProvider) método.
O provider parâmetro é uma implementação IFormatProvider cujo GetFormat método retorna um NumberFormatInfo objeto que fornece informações específicas da cultura sobre o formato de s. Há três maneiras de usar o provider parâmetro para fornecer informações de formatação personalizadas para a operação de análise:
Você pode passar o objeto real NumberFormatInfo que fornece informações de formatação. (Sua implementação de GetFormat simplesmente retorna a si mesma.)
Você pode passar um CultureInfo objeto que especifica a cultura cuja formatação deve ser usada. Sua NumberFormat propriedade fornece informações de formatação.
Você pode passar uma implementação personalizada IFormatProvider . Seu GetFormat método deve instanciar e retornar o NumberFormatInfo objeto que fornece informações de formatação.
Se provider for null, o NumberFormatInfo para a cultura atual é usado.
Confira também
Aplica-se a
Parse(String, NumberStyles)
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
Importante
Esta API não está em conformidade com CLS.
Converte a representação de cadeia de caracteres de um número em um estilo especificado em seu inteiro sem sinal de 16 bits equivalente.
Esse método não é compatível com CLS. A alternativa compatível com CLS é Parse(String, NumberStyles).
public:
static System::UInt16 Parse(System::String ^ s, System::Globalization::NumberStyles style);
[System.CLSCompliant(false)]
public static ushort Parse(string s, System.Globalization.NumberStyles style);
public static ushort Parse(string s, System.Globalization.NumberStyles style);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles -> uint16
static member Parse : string * System.Globalization.NumberStyles -> uint16
Public Shared Function Parse (s As String, style As NumberStyles) As UShort
Parâmetros
- s
- String
Uma cadeia de caracteres que representa o número a ser convertido. A cadeia de caracteres é interpretada usando o estilo especificado pelo style parâmetro.
- style
- NumberStyles
Uma combinação bit a bit dos valores de enumeração que especificam o formato permitido de s. Um valor típico a ser especificado é Integer.
Retornos
Um inteiro sem sinal de 16 bits equivalente ao número especificado em s.
- Atributos
Exceções
s é null.
style não é um NumberStyles valor.
-ou-
style não é uma combinação de AllowHexSpecifier valores e valores HexNumber .
s não está em um formato compatível com style.
s representa um número menor que UInt16.MinValue ou maior que UInt16.MaxValue.
-ou-
s inclui dígitos não zero e fracionários.
Exemplos
O exemplo a seguir tenta analisar cada elemento em uma matriz de cadeia de caracteres usando vários NumberStyles valores.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] values = { " 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.0e-2" };
NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite;
NumberStyles[] styles = { NumberStyles.None, whitespace,
NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace,
NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol,
NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint };
// Attempt to convert each number using each style combination.
foreach (string value in values)
{
Console.WriteLine("Attempting to convert '{0}':", value);
foreach (NumberStyles style in styles)
{
try {
ushort number = UInt16.Parse(value, style);
Console.WriteLine(" {0}: {1}", style, number);
}
catch (FormatException) {
Console.WriteLine(" {0}: Bad Format", style);
}
}
Console.WriteLine();
}
}
}
// The example display the following output:
// Attempting to convert ' 214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: 214
// Integer, AllowTrailingSign: 214
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '1,064':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: 1064
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '(0)':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '1241+':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: 1241
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert ' + 214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert ' +214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: 214
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '2153.0':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 2153
//
// Attempting to convert '1e03':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 1000
//
// Attempting to convert '1300.0e-2':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 13
open System
open System.Globalization
let values = [| " 214 "; "1,064"; "(0)"; "1241+"; " + 214 "; " +214 "; "2153.0"; "1e03"; "1300.0e-2" |]
let whitespace = NumberStyles.AllowLeadingWhite ||| NumberStyles.AllowTrailingWhite
let styles =
[| NumberStyles.None; whitespace
NumberStyles.AllowLeadingSign ||| NumberStyles.AllowTrailingSign ||| whitespace
NumberStyles.AllowThousands ||| NumberStyles.AllowCurrencySymbol
NumberStyles.AllowExponent ||| NumberStyles.AllowDecimalPoint |]
// Attempt to convert each number using each style combination.
for value in values do
printfn $"Attempting to convert '{value}':"
for style in styles do
try
let number = UInt16.Parse(value, style)
printfn $" {style}: {number}"
with :? FormatException ->
printfn $" {style}: Bad Format"
printfn ""
// The example display the following output:
// Attempting to convert ' 214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: 214
// Integer, AllowTrailingSign: 214
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '1,064':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: 1064
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '(0)':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '1241+':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: 1241
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert ' + 214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert ' +214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: 214
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '2153.0':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 2153
//
// Attempting to convert '1e03':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 1000
//
// Attempting to convert '1300.0e-2':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 13
Imports System.Globalization
Module Example
Public Sub Main()
Dim values() As String = { " 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.0e-2" }
Dim whitespace As NumberStyles = NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite
Dim styles() As NumberStyles = { NumberStyles.None, _
whitespace, _
NumberStyles.AllowLeadingSign Or NumberStyles.AllowTrailingSign Or whitespace, _
NumberStyles.AllowThousands Or NumberStyles.AllowCurrencySymbol, _
NumberStyles.AllowExponent Or NumberStyles.AllowDecimalPoint }
' Attempt to convert each number using each style combination.
For Each value As String In values
Console.WriteLine("Attempting to convert '{0}':", value)
For Each style As NumberStyles In styles
Try
Dim number As UShort = UInt16.Parse(value, style)
Console.WriteLine(" {0}: {1}", style, number)
Catch e As FormatException
Console.WriteLine(" {0}: Bad Format", style)
End Try
Next
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' Attempting to convert ' 214 ':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: 214
' Integer, AllowTrailingSign: 214
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert '1,064':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: 1064
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert '(0)':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert '1241+':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: 1241
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert ' + 214 ':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert ' +214 ':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: 214
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert '2153.0':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: 2153
'
' Attempting to convert '1e03':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: 1000
'
' Attempting to convert '1300.0e-2':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: 13
Comentários
O style parâmetro define os elementos de estilo (como espaço em branco, o símbolo de sinal positivo ou negativo, o símbolo do separador de grupo ou o símbolo de ponto decimal) que são permitidos no s parâmetro para que a operação de análise tenha êxito.
style deve ser uma combinação de sinalizadores de bits da NumberStyles enumeração. O style parâmetro torna essa sobrecarga de método útil quando s contém a representação de cadeia de caracteres de um valor hexadecimal, quando o sistema de números (decimal ou hexadecimal) representado por s é conhecido apenas em tempo de execução ou quando você deseja desabilitar o espaço em branco ou um símbolo de sinal.s
Dependendo do valor de style, o s parâmetro pode incluir os seguintes elementos:
[ws][$][sign][digits,]digits[.fractional_digits][E[sign]exponential_digits][ws]
Elementos em colchetes ([ e ]) são opcionais. Se style incluir NumberStyles.AllowHexSpecifier, o s parâmetro poderá conter os seguintes elementos:
[ws]hexdigits[ws]
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 incluir o style sinalizador e pode aparecer no final de NumberStyles.AllowLeadingWhite se s incluir o styleNumberStyles.AllowTrailingWhite sinalizador. |
| $ | Um símbolo de moeda específico à cultura. Sua posição na cadeia de caracteres é definida pelas propriedades e NumberFormatInfo.CurrencyNegativePattern pela NumberFormatInfo.CurrencyPositivePattern cultura atual. O símbolo de moeda da cultura atual poderá aparecer s se style incluir o NumberStyles.AllowCurrencySymbol sinalizador. |
| assinar | Um sinal opcional. O sinal pode aparecer no início de s se incluir o style sinalizador e pode aparecer no final de NumberStyles.AllowLeadingSign se s incluir o styleNumberStyles.AllowTrailingSign sinalizador. Parênteses podem ser usados s para indicar um valor negativo se style incluir o NumberStyles.AllowParentheses sinalizador. No entanto, o símbolo de sinal negativo só pode ser usado com zero; caso contrário, o método gerará um OverflowException. |
|
Dígitos Fractional_digits exponential_digits |
Uma sequência de dígitos de 0 a 9. Para fractional_digits, somente o dígito 0 é válido. |
| , | Um símbolo de separador de grupo específico à cultura. O separador de grupo da cultura atual poderá aparecer s se style incluir o NumberStyles.AllowThousands sinalizador. |
| . | Um símbolo de ponto decimal específico da cultura. O símbolo de ponto decimal da cultura atual poderá aparecer s se style incluir o NumberStyles.AllowDecimalPoint sinalizador. Somente o dígito 0 pode aparecer como um dígito fracionário para que a operação de análise tenha êxito; se fractional_digits incluir qualquer outro dígito, um FormatException será gerado. |
| E | O caractere "e" ou "E", que indica que o valor é representado na notação exponencial (científica). O s parâmetro pode representar um número na notação exponencial se style incluir o NumberStyles.AllowExponent sinalizador. |
| hexdigits | Uma sequência de dígitos hexadecimal de 0 a f ou 0 a F. |
Nota
Todos os caracteres s NUL de terminação (U+0000) são ignorados pela operação de análise, independentemente do valor do style argumento.
Uma cadeia de caracteres somente com dígitos (que NumberStyles.None corresponde ao estilo) sempre será analisada com êxito se estiver no intervalo do UInt16 tipo. A maioria dos elementos de controle de membros restantes NumberStyles que podem estar presentes, mas não precisam estar presentes, na cadeia de caracteres de entrada. A tabela a seguir indica como os membros individuais NumberStyles afetam os elementos que podem estar presentes em s.
Valor NumberStyles |
Elementos permitidos s além de dígitos |
|---|---|
| None | Somente o elemento de dígitos . |
| AllowDecimalPoint | O ponto decimal (.) e os elementos de dígitos fracionários . |
| AllowExponent | O caractere "e" ou "E", que indica notação exponencial, juntamente com exponential_digits. |
| AllowLeadingWhite | O elemento ws no início de s. |
| AllowTrailingWhite | O elemento ws no final de s. |
| AllowLeadingSign | O elemento sign no início de s. |
| AllowTrailingSign | O elemento sign no final de s. |
| AllowParentheses | O elemento sign na forma de parênteses que inclui o valor numérico. |
| AllowThousands | O elemento separador de grupo (,). |
| AllowCurrencySymbol | O elemento currency ($). |
| Currency | Todos os elementos. No entanto, s não é possível representar um número hexadecimal ou um número em notação exponencial. |
| Float | O elemento ws no início ou no final de s, assinar no início e so símbolo de ponto decimal (.). O s parâmetro também pode usar notação exponencial. |
| Number | Os wselementos separador signde grupo (,) e ponto decimal (.). |
| Any | Todos os elementos. No entanto, s não é possível representar um número hexadecimal. |
Ao contrário dos outros NumberStyles valores, que permitem, mas não exigem, a presença de elementos de estilo específicos, so valor de NumberStyles.AllowHexSpecifier estilo significa que os caracteres s numéricos individuais sempre são interpretados como caracteres hexadecimal. Os caracteres hexadecimal válidos são 0-9, A-F e a-f. Não há suporte para um prefixo, como "0x", e faz com que a operação de análise falhe. Os únicos outros sinalizadores que podem ser combinados com o style parâmetro são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A NumberStyles enumeração inclui um estilo de número composto, NumberStyles.HexNumberque inclui sinalizadores de espaço em branco.)
Nota
Se s for a representação de cadeia de caracteres de um número hexadecimal, ela não poderá ser precedida por qualquer decoração (como 0x ou &h) que a diferencie como um número hexadecimal. Isso faz com que a conversão falhe.
O s parâmetro é analisado usando as informações de formatação em um NumberFormatInfo objeto inicializado para a cultura atual do sistema. Para especificar a cultura cujas informações de formatação são usadas para a operação de análise, chame a Parse(String, NumberStyles, IFormatProvider) sobrecarga.
Confira também
Aplica-se a
Parse(ReadOnlySpan<Char>, IFormatProvider)
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
Analisa um intervalo de caracteres em um valor.
public:
static System::UInt16 Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<System::UInt16>::Parse;
public static ushort Parse(ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> uint16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As UShort
Parâmetros
- s
- ReadOnlySpan<Char>
O intervalo de caracteres a serem analisados.
- provider
- IFormatProvider
Um objeto que fornece informações de formatação específicas da cultura sobre s.
Retornos
O resultado da análise s.
Implementações
Aplica-se a
Parse(ReadOnlySpan<Byte>, IFormatProvider)
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
Analisa um intervalo de caracteres UTF-8 em um valor.
public:
static System::UInt16 Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<System::UInt16>::Parse;
public static ushort Parse(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> uint16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As UShort
Parâmetros
- utf8Text
- ReadOnlySpan<Byte>
O intervalo de caracteres UTF-8 a serem analisados.
- provider
- IFormatProvider
Um objeto que fornece informações de formatação específicas da cultura sobre utf8Text.
Retornos
O resultado da análise utf8Text.
Implementações
Aplica-se a
Parse(String)
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
- Origem:
- UInt16.cs
Importante
Esta API não está em conformidade com CLS.
- Alternativa em conformidade com CLS
- System.Int32.Parse(String)
Converte a representação de cadeia de caracteres de um número em seu equivalente inteiro sem sinal de 16 bits.
public:
static System::UInt16 Parse(System::String ^ s);
[System.CLSCompliant(false)]
public static ushort Parse(string s);
public static ushort Parse(string s);
[<System.CLSCompliant(false)>]
static member Parse : string -> uint16
static member Parse : string -> uint16
Public Shared Function Parse (s As String) As UShort
Parâmetros
- s
- String
Uma cadeia de caracteres que representa o número a ser convertido.
Retornos
Um inteiro sem sinal de 16 bits equivalente ao número contido em s.
- Atributos
Exceções
s é null.
s não está no formato correto.
s representa um número menor que UInt16.MinValue ou maior que UInt16.MaxValue.
Exemplos
O exemplo a seguir chama o Parse(String) método para converter cada elemento em uma matriz de cadeia de caracteres em um inteiro de 16 bits sem sinal.
using System;
public class Example
{
public static void Main()
{
string[] values = { "-0", "17", "-12", "185", "66012", "+0",
"", null, "16.1", "28.0", "1,034" };
foreach (string value in values)
{
try {
ushort number = UInt16.Parse(value);
Console.WriteLine("'{0}' --> {1}", value, number);
}
catch (FormatException) {
Console.WriteLine("'{0}' --> Bad Format", value);
}
catch (OverflowException) {
Console.WriteLine("'{0}' --> OverflowException", value);
}
catch (ArgumentNullException) {
Console.WriteLine("'{0}' --> Null", value);
}
}
}
}
// The example displays the following output:
// '-0' --> 0
// '17' --> 17
// '-12' --> OverflowException
// '185' --> 185
// '66012' --> OverflowException
// '+0' --> 0
// '' --> Bad Format
// '' --> Null
// '16.1' --> Bad Format
// '28.0' --> Bad Format
// '1,034' --> Bad Format
open System
let values =
[| "-0"; "17"; "-12"; "185"; "66012"; "+0"
""; null; "16.1"; "28.0"; "1,034" |]
for value in values do
try
let number = UInt16.Parse value
printfn $"'{value}' --> {number}"
with
| :? FormatException ->
printfn $"'{value}' --> Bad Format"
| :? OverflowException ->
printfn $"'{value}' --> OverflowException"
| :? ArgumentNullException ->
printfn $"'{value}' --> Null"
// The example displays the following output:
// '-0' --> 0
// '17' --> 17
// '-12' --> OverflowException
// '185' --> 185
// '66012' --> OverflowException
// '+0' --> 0
// '' --> Bad Format
// '' --> Null
// '16.1' --> Bad Format
// '28.0' --> Bad Format
// '1,034' --> Bad Format
Module Example
Public Sub Main()
Dim values() As String = { "-0", "17", "-12", "185", "66012", _
"+0", "", Nothing, "16.1", "28.0", _
"1,034" }
For Each value As String In values
Try
Dim number As UShort = UInt16.Parse(value)
Console.WriteLine("'{0}' --> {1}", value, number)
Catch e As FormatException
Console.WriteLine("'{0}' --> Bad Format", value)
Catch e As OverflowException
Console.WriteLine("'{0}' --> OverflowException", value)
Catch e As ArgumentNullException
Console.WriteLine("'{0}' --> Null", value)
End Try
Next
End Sub
End Module
' The example displays the following output:
' '-0' --> 0
' '17' --> 17
' '-12' --> OverflowException
' '185' --> 185
' '66012' --> OverflowException
' '+0' --> 0
' '' --> Bad Format
' '' --> Null
' '16.1' --> Bad Format
' '28.0' --> Bad Format
' '1,034' --> Bad Format
Comentários
O s parâmetro deve ser a representação de cadeia de caracteres de um número no formulário a seguir.
[ws][sign]digits[ws]
Elementos em colchetes ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.
| Elemento | Descrição |
|---|---|
| Ws | Espaço em branco opcional. |
| assinar | Um sinal opcional. Caracteres de sinal válidos são determinados pelas propriedades e NumberFormatInfo.NegativeSign pela NumberFormatInfo.PositiveSign cultura atual. No entanto, o símbolo de sinal negativo só pode ser usado com zero; caso contrário, o método gerará um OverflowException. |
| Dígitos | Uma sequência de dígitos variando de 0 a 9. Todos os zeros à esquerda são ignorados. |
Nota
A cadeia de caracteres especificada pelo s parâmetro é interpretada usando o NumberStyles.Integer estilo. Ele não pode conter separadores de grupo ou separador decimal e não pode ter uma parte decimal.
O s parâmetro é analisado usando as informações de formatação em um System.Globalization.NumberFormatInfo objeto inicializado para a cultura atual do sistema. Para obter mais informações, consulte NumberFormatInfo.CurrentInfo. Para analisar uma cadeia de caracteres usando as informações de formatação de uma cultura específica, use o Parse(String, IFormatProvider) método.