UInt16.Parse Método

Definição

Converte a representação da cadeia de um número para o seu equivalente inteiro sem sinal de 16 bits.

Sobrecargas

Name Description
Parse(String, NumberStyles, IFormatProvider)

Converte a representação da cadeia de um número num estilo especificado e formato específico de cultura para o seu equivalente inteiro sem sinal de 16 bits.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Converte a representação em expansão de um número num estilo especificado e formato específico de cultura para o seu equivalente inteiro sem sinal de 16 bits.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Analisa um intervalo de caracteres UTF-8 num valor.

Parse(String, IFormatProvider)

Converte a representação da cadeia de um número num formato específico de cultura para o seu equivalente inteiro sem sinal de 16 bits.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Divide um intervalo de caracteres num valor.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Analisa um intervalo de caracteres UTF-8 num valor.

Parse(String)

Converte a representação da cadeia de um número para o seu equivalente inteiro sem sinal de 16 bits.

Parse(String, NumberStyles)

Converte a representação da cadeia de um número num estilo especificado para o seu equivalente inteiro sem sinal de 16 bits.

Este método não é compatível com CLS. A alternativa compatível com CLS é Parse(String, NumberStyles).

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 da cadeia de um número num estilo especificado e formato específico de cultura para o seu equivalente inteiro sem sinal de 16 bits.

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 que representa o número a converter. A cadeia é 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 especificar é Integer.

provider
IFormatProvider

Um objeto que fornece informação de formatação específica de cultura sobre s.

Devoluções

Um inteiro não assinado de 16 bits equivalente ao número especificado em s.

Implementações

Atributos

Exceções

style não é um NumberStyles valor.

-ou-

style não é uma combinação de AllowHexSpecifier valores e HexNumber .

s não está num formato compatível com style.

s representa um número que é inferior a UInt16.MinValue ou superior a UInt16.MaxValue.

-ou-

s inclui dígitos fracionados e não nulos.

Exemplos

O exemplo seguinte utiliza o Parse(String, NumberStyles, IFormatProvider) método para converter várias representações de números em cadeia 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.

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]

Os elementos entre parênteses retos ([ e ]) são opcionais. Se style inclui NumberStyles.AllowHexSpecifier, o s parâmetro pode 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 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 cadeia é definida pela CurrencyPositivePattern propriedade do NumberFormatInfo objeto que é devolvida pelo GetFormat método do provider parâmetro. O símbolo da moeda pode aparecer se sstyle incluir a NumberStyles.AllowCurrencySymbol bandeira.
assinar Um sinal opcional. (O método lança um OverflowException ses, inclui um sinal negativo e representa um número não nulo.) 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 antes dos dígitos.
NumberStyles.AllowTrailingSign Um sinal depois dos dígitos.
NumberStyles.AllowParentheses Parênteses entre dígitos antes e depois para indicar um valor negativo.
NumberStyles.AllowThousands O elemento separador de grupo (,).
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 de 0 a 9, de a a f, e de A 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 com NumberStyles.AllowHexSpecifier e NumberStyles.AllowLeadingWhiteNumberStyles.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.

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<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 em expansão de um número num estilo especificado e formato específico de cultura para o seu equivalente inteiro sem sinal de 16 bits.

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 espaço que contém os caracteres que representam o número a converter. O vão é 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 especificar é Integer.

provider
IFormatProvider

Um objeto que fornece informação de formatação específica de cultura sobre s.

Devoluções

Um inteiro não assinado 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 num 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>

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(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 da cadeia de um número num formato específico de cultura para o seu equivalente inteiro sem sinal de 16 bits.

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 que representa o número a converter.

provider
IFormatProvider

Um objeto que fornece informação de formatação específica de cultura sobre s.

Devoluções

Um inteiro não assinado de 16 bits equivalente ao número especificado em s.

Implementações

Atributos

Exceções

s não está no formato correto.

s representa um número inferior ao UInt16.MinValue ou superior ao UInt16.MaxValue.

Exemplos

O exemplo seguinte instancia uma cultura personalizada que usa dois signos de mais (++) como sinal positivo. Depois, chama o Parse(String, IFormatProvider) método para analisar um array de cadeias usando CultureInfo objetos que representam tanto esta cultura personalizada como a cultura invariante.

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.

Observações

O s parâmetro contém um número da forma:

[ws][sinal]dígitos[ws]

Itens entre parênteses ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.

Elemento Descrição
ws Espaço em branco opcional.
sign Um sinal opcional, ou um sinal negativo se s representar o valor zero.
dígitos Uma sequência de dígitos que varia de 0 a 9.

O parâmetro s é interpretado usando o NumberStyles.Integer estilo. Para além dos dígitos decimais do valor do byte, apenas espaços iniciais e finais juntamente com um sinal inicial são permitidos. (Se o sinal negativo estiver presente, s deve representar um valor zero ou o método lança um OverflowException.) Para definir explicitamente os elementos de estilo juntamente com a informação de formatação específica da cultura que pode estar presente em s, utilize 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 para a cultura atual é usado.

Ver também

Aplica-se a

Parse(ReadOnlySpan<Char>, IFormatProvider)

Origem:
UInt16.cs
Origem:
UInt16.cs
Origem:
UInt16.cs
Origem:
UInt16.cs
Origem:
UInt16.cs

Divide um intervalo de caracteres num 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 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(ReadOnlySpan<Byte>, IFormatProvider)

Origem:
UInt16.cs
Origem:
UInt16.cs
Origem:
UInt16.cs
Origem:
UInt16.cs

Analisa um intervalo de caracteres UTF-8 num 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>

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(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 da cadeia de um número para o 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 que representa o número a converter.

Devoluções

Um inteiro sem sinal de 16 bits equivalente ao número contido em s.

Atributos

Exceções

s não está no formato correto.

s representa um número inferior ao UInt16.MinValue ou superior ao UInt16.MaxValue.

Exemplos

O exemplo seguinte chama o Parse(String) método para converter cada elemento de um array de strings num inteiro não assinado de 16 bits.

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

Observações

O s parâmetro deve ser a representação em cadeia de um número na seguinte 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. Caracteres de signo válidos são determinados pelas NumberFormatInfo.NegativeSign propriedades e NumberFormatInfo.PositiveSign da cultura atual. No entanto, o símbolo do signo negativo só pode ser usado com zero; caso contrário, o método lança um OverflowException.
dígitos Uma sequência de dígitos que varia de 0 a 9. Quaisquer zeros à esquerda são ignorados.

Note

A cadeia especificada pelo s parâmetro é interpretada usando o NumberStyles.Integer estilo. Não pode conter separadores de grupo ou separadores decimais, nem pode ter uma parte decimal.

O s parâmetro é analisado utilizando a informação de formatação num System.Globalization.NumberFormatInfo objeto que é inicializado 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 uma cultura específica, use o Parse(String, IFormatProvider) método.

Ver 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 da cadeia de um número num estilo especificado para o seu equivalente inteiro sem sinal de 16 bits.

Este 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 que representa o número a converter. A cadeia é 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 especificar é Integer.

Devoluções

Um inteiro não assinado de 16 bits equivalente ao número especificado em s.

Atributos

Exceções

style não é um NumberStyles valor.

-ou-

style não é uma combinação de AllowHexSpecifier valores e HexNumber .

s não está num formato compatível com style.

s representa um número inferior ao UInt16.MinValue ou superior ao UInt16.MaxValue.

-ou-

s inclui dígitos fracionados e não nulos.

Exemplos

O exemplo seguinte tenta analisar cada elemento num array de NumberStyles cadeias usando vários 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

Observações

O style parâmetro define os elementos de estilo (como espaço em branco, símbolo de sinal positivo ou negativo, símbolo de separador de grupo ou símbolo de ponto decimal) que são permitidos no s parâmetro para que a operação de análise sintática tenha sucesso. style deve ser uma combinação de flags de bits da NumberStyles enumeração. O style parâmetro torna este método sobrecarregado útil quando s contém a representação em cadeia de um valor hexadecimal, quando o sistema numérico (decimal ou hexadecimal) representado por s é conhecido apenas em tempo de execução, ou quando se pretende impedir espaço em branco ou um símbolo de sinal em s.

Dependendo do valor de style, o s parâmetro pode incluir os seguintes elementos:

[ws][$][signo][dígitos,]dígitos[.fractional_digits][E[sign]exponential_digits][ws]

Os elementos entre parênteses retos ([ e ]) são opcionais. Se style inclui NumberStyles.AllowHexSpecifier, o s parâmetro pode 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 if style inclui a NumberStyles.AllowLeadingWhite bandeira, e pode aparecer no final de s if style inclui a NumberStyles.AllowTrailingWhite bandeira.
$ Um símbolo monetário específico de cada cultura. A sua posição na corda é definida pelas NumberFormatInfo.CurrencyNegativePattern propriedades e NumberFormatInfo.CurrencyPositivePattern 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 incluir a style bandeira, e pode aparecer no final de NumberStyles.AllowLeadingSign se s incluir a styleNumberStyles.AllowTrailingSign bandeira. Parênteses podem ser usados s para indicar um valor negativo se style incluir a NumberStyles.AllowParentheses bandeira. No entanto, o símbolo do signo negativo só pode ser usado com zero; caso contrário, o método lança um OverflowException.
dígitos

fractional_digits

exponential_digits
Uma sequência de dígitos de 0 a 9. Para fractional_digits, apenas o dígito 0 é válido.
, Um símbolo separador de grupo específico de cada cultura. O separador de grupo da cultura atual pode aparecer em s se style incluir a NumberStyles.AllowThousands bandeira.
. 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. Apenas o dígito 0 pode aparecer como um dígito fracionário para que a operação de análise sintética tenha sucesso; Se fractional_digits incluir qualquer outro dígito, a FormatException é lançado.
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.
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 (que corresponde ao NumberStyles.None estilo) analisa sempre com sucesso se estiver no intervalo do UInt16 tipo. 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.

NumberStyles valor Elementos permitidos s além dos dígitos
None Apenas o elemento dígitos .
AllowDecimalPoint Os elementos de ponto decimal (.) e de dígitos fracionários .
AllowExponent O carácter "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 signo no início de s.
AllowTrailingSign O elemento signo no final de s.
AllowParentheses O elemento do signo na forma de parênteses que envolvem o valor numérico.
AllowThousands O elemento separador de grupo (,).
AllowCurrencySymbol O elemento da moeda ($).
Currency Todos os elementos. No entanto, s não pode representar um número hexadecimal ou um número em notação exponencial.
Float O elemento ws no início ou fim de s, sinal no início de s, e o símbolo da vírgula decimal (.). O s parâmetro também pode usar notação exponencial.
Number Os wselementos , sign, separador de grupo (,) e ponto decimal (.).
Any Todos os elementos. No entanto, s não pode 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 em s, o NumberStyles.AllowHexSpecifier valor de estilo significa que os caracteres numéricos individuais em s são sempre interpretados como caracteres hexadecimais. Caracteres 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. Os únicos outros flags que podem ser combinados com o style parâmetro 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 s for a representação em cadeia de um número hexadecimal, não pode ser precedida por qualquer decoração (como 0x ou &h) que a diferencie como número hexadecimal. Isto faz com que a conversão falhe.

O s parâmetro é analisado utilizando a informação de formatação num NumberFormatInfo objeto que é inicializado para a cultura do sistema atual. Para especificar a cultura cuja informação de formatação é usada para a operação de análise sintática, chame-se a Parse(String, NumberStyles, IFormatProvider) sobrecarga.

Ver também

Aplica-se a