Int16.Parse Método

Definição

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

Sobrecargas

Name Description
Parse(String)

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

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Analisa um intervalo de caracteres UTF-8 num valor.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Divide um intervalo de caracteres num valor.

Parse(String, NumberStyles)

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

Parse(String, IFormatProvider)

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

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Analisa um intervalo de caracteres UTF-8 num valor.

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 com sinal de 16 bits.

Parse(String, NumberStyles, IFormatProvider)

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

Parse(String)

Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs

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

public:
 static short Parse(System::String ^ s);
public static short Parse(string s);
static member Parse : string -> int16
Public Shared Function Parse (s As String) As Short

Parâmetros

s
String

Uma cadeia contendo um número a converter.

Devoluções

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

Exceções

s não está no formato correto.

s representa um número menor que Int16.MinValue ou maior que Int16.MaxValue.

Exemplos

O exemplo seguinte demonstra como converter um valor de cadeia num valor inteiro assinado de 16 bits usando o Int16.Parse(String) método. O valor inteiro resultante é então apresentado à consola.

string value;
short number;

value = " 12603 ";
try
{
   number = Int16.Parse(value);
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
   Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
                     value);
}

value = " 16,054";
try
{
   number = Int16.Parse(value);
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
   Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
                     value);
}

value = " -17264";
try
{
   number = Int16.Parse(value);
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
   Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
                     value);
}
// The example displays the following output to the console:
//       Converted ' 12603 ' to 12603.
//       Unable to convert ' 16,054' to a 16-bit signed integer.
//       Converted ' -17264' to -17264.
let value = " 12603 "
try
    let number = Int16.Parse value
    printfn $"Converted '{value}' to {number}." 
with :? FormatException -> 
    printfn $"Unable to convert '{value}' to a 16-bit signed integer."

let value = " 16,054"
try
    let number = Int16.Parse value
    printfn $"Converted '{value}' to {number}."
with :? FormatException ->
    printfn "Unable to convert '{value}' to a 16-bit signed integer."
                    
let value = " -17264"
try
    let number = Int16.Parse value
    printfn $"Converted '{value}' to {number}."
with :? FormatException ->
    printfn "Unable to convert '{value}' to a 16-bit signed integer."
    

// The example displays the following output to the console:
//       Converted ' 12603 ' to 12603.
//       Unable to convert ' 16,054' to a 16-bit signed integer.
//       Converted ' -17264' to -17264.
Dim value As String
Dim number As Short

value = " 12603 "
Try
   number = Short.Parse(value)
   Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
   Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.", _
                     value)
End Try

value = " 16,054"
Try
   number = Short.Parse(value)
   Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
   Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.", _
                     value)
End Try
                        
value = " -17264"
Try
   number = Short.Parse(value)
   Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
   Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.", _
                     value)
End Try
' The example displays the following output to the console:
'       Converted ' 12603 ' to 12603.
'       Unable to convert ' 16,054' to a 16-bit signed integer.
'       Converted ' -17264' to -17264.

Observações

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

[ws][signo] dígitos[ws]

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

Elemento Descrição
ws Espaço em branco opcional.
assinar Um sinal opcional.
dígitos Uma sequência de dígitos que varia de 0 a 9.

O s parâmetro é interpretado usando o NumberStyles.Integer estilo. Para além dos dígitos decimais do valor inteiro, apenas os espaços iniciais e finais juntamente com um sinal à esquerda são permitidos. Para definir explicitamente os elementos de estilo que podem estar presentes em s, use o Int16.Parse(String, NumberStyles) ou o Parse método.

O s parâmetro é analisado usando a informação de formatação num NumberFormatInfo objeto que é inicializado para a cultura do sistema atual. Para obter mais informações, veja CurrentInfo. Para analisar uma cadeia usando a informação de formatação de outra cultura, use o Int16.Parse(String, IFormatProvider) ou o Int16.Parse(String, NumberStyles, IFormatProvider) método.

Ver também

Aplica-se a

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs

Analisa um intervalo de caracteres UTF-8 num valor.

public:
 static short Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<short>::Parse;
public static short Parse(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> int16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As Short

Parâmetros

utf8Text
ReadOnlySpan<Byte>

A extensão de caracteres UTF-8 para analisar.

provider
IFormatProvider

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

Devoluções

O resultado da análise sintática utf8Text.

Implementações

Aplica-se a

Parse(ReadOnlySpan<Char>, IFormatProvider)

Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs

Divide um intervalo de caracteres num valor.

public:
 static short Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<short>::Parse;
public static short Parse(ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> int16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As Short

Parâmetros

s
ReadOnlySpan<Char>

O número de personagens a analisar.

provider
IFormatProvider

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

Devoluções

O resultado da análise sintática s.

Implementações

Aplica-se a

Parse(String, NumberStyles)

Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs

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

public:
 static short Parse(System::String ^ s, System::Globalization::NumberStyles style);
public static short Parse(string s, System.Globalization.NumberStyles style);
static member Parse : string * System.Globalization.NumberStyles -> int16
Public Shared Function Parse (s As String, style As NumberStyles) As Short

Parâmetros

s
String

Uma cadeia contendo um número a converter.

style
NumberStyles

Uma combinação bit a bit dos valores de enumeração que indica os elementos de estilo que podem estar presentes em s. Um valor típico a especificar é Integer.

Devoluções

Um inteiro com sinal de 16 bits equivalente ao número especificado em s.

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 menor que Int16.MinValue ou maior que Int16.MaxValue.

-ou-

s inclui dígitos fracionários não nulos.

Exemplos

O exemplo seguinte utiliza o Int16.Parse(String, NumberStyles) método para analisar as representações de cadeias de Int16 valores usando a cultura en-US.

using System;
using System.Globalization;

public class ParseSample
{
   public static void Main()
   {
      string value;
      NumberStyles style;

      // Parse a number with a thousands separator (throws an exception).
      value = "14,644";
      style = NumberStyles.None;
      ParseToInt16(value, style);

      style = NumberStyles.AllowThousands;
      ParseToInt16(value, style);

      // Parse a number with a thousands separator and decimal point.
      value = "14,644.00";
      style = NumberStyles.AllowThousands | NumberStyles.Integer |
              NumberStyles.AllowDecimalPoint;
      ParseToInt16(value, style);

      // Parse a number with a fractional component (throws an exception).
      value = "14,644.001";
      ParseToInt16(value, style);

      // Parse a number in exponential notation.
      value = "145E02";
      style = style | NumberStyles.AllowExponent;
      ParseToInt16(value, style);

      // Parse a number in exponential notation with a positive sign.
      value = "145E+02";
      ParseToInt16(value, style);

      // Parse a number in exponential notation with a negative sign
      // (throws an exception).
      value = "145E-02";
      ParseToInt16(value, style);
   }

   private static void ParseToInt16(string value, NumberStyles style)
   {
      try
      {
         short number = Int16.Parse(value, style);
         Console.WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException)
      {
         Console.WriteLine("Unable to parse '{0}' with style {1}.", value,
                           style.ToString());
      }
      catch (OverflowException)
      {
         Console.WriteLine("'{0}' is out of range of the Int16 type.", value);
      }
   }
}
// The example displays the following output to the console:
//       Unable to parse '14,644' with style None.
//       Converted '14,644' to 14644.
//       Converted '14,644.00' to 14644.
//       '14,644.001' is out of range of the Int16 type.
//       Converted '145E02' to 14500.
//       Converted '145E+02' to 14500.
//       '145E-02' is out of range of the Int16 type.
open System
open System.Globalization

let parseToInt16 (value: string) (style: NumberStyles) =
    try
        let number = Int16.Parse(value, style)
        printfn $"Converted '{value}' to {number}."
    with
    | :? FormatException ->
        printfn $"Unable to parse '{value}' with style {style}."
    | :? OverflowException ->
        printfn $"'{value}' is out of range of the Int16 type."

[<EntryPoint>]
let main _ =
    // Parse a number with a thousands separator (throws an exception).
    let value = "14,644"
    let style = NumberStyles.None
    parseToInt16 value style

    let style = NumberStyles.AllowThousands
    parseToInt16 value style

    // Parse a number with a thousands separator and decimal point.
    let value = "14,644.00"
    let style = NumberStyles.AllowThousands ||| NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
    parseToInt16 value style

    // Parse a number with a fractional component (throws an exception).
    let value = "14,644.001"
    parseToInt16 value style

    // Parse a number in exponential notation.
    let value = "145E02"
    let style = style ||| NumberStyles.AllowExponent
    parseToInt16 value style

    // Parse a number in exponential notation with a positive sign.
    let value = "145E+02"
    parseToInt16 value style

    // Parse a number in exponential notation with a negative sign
    // (throws an exception).
    let value = "145E-02"
    parseToInt16 value style

    0

// The example displays the following output to the console:
//       Unable to parse '14,644' with style None.
//       Converted '14,644' to 14644.
//       Converted '14,644.00' to 14644.
//       '14,644.001' is out of range of the Int16 type.
//       Converted '145E02' to 14500.
//       Converted '145E+02' to 14500.
//       '145E-02' is out of range of the Int16 type.
Imports System.Globalization

Module ParseSample
   Public Sub Main()
      Dim value As String 
      Dim style As NumberStyles
      
      ' Parse a number with a thousands separator (throws an exception).
      value = "14,644"
      style = NumberStyles.None
      ParseToInt16(value, style)
      
      style = NumberStyles.AllowThousands
      ParseToInt16(value, style)
      
      ' Parse a number with a thousands separator and decimal point.
      value = "14,644.00"
      style = NumberStyles.AllowThousands Or NumberStyles.Integer Or _
              NumberStyles.AllowDecimalPoint
      ParseToInt16(value, style)
      
      ' Parse a number with a fractional component (throws an exception).
      value = "14,644.001"
      ParseToInt16(value, style)
      
      ' Parse a number in exponential notation.
      value = "145E02"
      style = style Or NumberStyles.AllowExponent
      ParseToInt16(value, style)
      
      ' Parse a number in exponential notation with a positive sign.
      value = "145E+02"
      ParseToInt16(value, style)
      
      ' Parse a number in exponential notation with a negative sign
      ' (throws an exception).
      value = "145E-02"
      ParseToInt16(value, style)
   End Sub
   
   Private Sub ParseToInt16(value As String, style As NumberStyles)
      Try
         Dim number As Short = Int16.Parse(value, style)
         Console.WriteLine("Converted '{0}' to {1}.", value, number)
      Catch e As FormatException
         Console.WriteLine("Unable to parse '{0}' with style {1}.", value, _
                           style.ToString())
      Catch e As OverflowException
         Console.WriteLine("'{0}' is out of range of the Int16 type.", value)
      End Try
   End Sub   
End Module
' The example displays the following output to the console:
'       Unable to parse '14,644' with style None.
'       Converted '14,644' to 14644.
'       Converted '14,644.00' to 14644.
'       '14,644.001' is out of range of the Int16 type.
'       Converted '145E02' to 14500.
'       Converted '145E+02' to 14500.
'       '145E-02' is out of range of the Int16 type.

Observações

O style parâmetro define os elementos de estilo (como espaços em branco ou um símbolo de sinal) 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][$][sinal][dígitos,]dígitos[.fractional_digits][dígitos e[signos][ws]

Ou, se style incluir AllowHexSpecifier:

[ws]hexdigits[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. O espaço em branco pode aparecer no início de s se style inclui a NumberStyles.AllowLeadingWhite bandeira, ou no final de s se style inclui a NumberStyles.AllowTrailingWhite bandeira.
$ Um símbolo monetário específico de cada cultura. A sua posição na corda é definida pelas NumberFormatInfo.CurrencyPositivePattern propriedades e NumberFormatInfo.CurrencyNegativePattern da cultura atual. O símbolo monetário da cultura atual pode aparecer se sstyle incluir a NumberStyles.AllowCurrencySymbol bandeira.
assinar Um sinal opcional. O sinal pode aparecer no início de s se inclui a style bandeira, e pode aparecer no final de NumberStyles.AllowLeadingSign se s inclui a styleNumberStyles.AllowTrailingSign bandeira. Parênteses podem ser usados s para indicar um valor negativo se style incluir a NumberStyles.AllowParentheses bandeira.
dígitos Uma sequência de dígitos de 0 a 9.
, Um símbolo separador de milhares específico de cultura. O símbolo separador dos milhares da cultura atual pode aparecer se sstyle 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.
fractional_digits Uma sequência do dígito 0. Dígitos fracionários podem aparecer em s se style incluir a NumberStyles.AllowDecimalPoint bandeira. Se qualquer dígito diferente de 0 aparecer em fractional_digits, o método gera um OverflowException.
e O carácter 'e' ou 'E', que indica que s pode ser representado em notação exponencial. O s parâmetro pode representar um número em notação exponencial se style incluir a NumberStyles.AllowExponent bandeira. No entanto, o s parâmetro deve representar um número no intervalo do Int16 tipo de dado e não pode ter um componente fracionário diferente de zero.
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 sequência apenas com dígitos (que corresponde ao NumberStyles.None estilo) faz sempre pars com sucesso. A maioria dos membros restantes NumberStyles controla elementos que podem estar, mas não são obrigados a estar, nesta cadeia de entrada. A tabela seguinte indica como os membros individuais NumberStyles afetam os elementos que podem estar presentes em s.

Valores de NumberStyles não compostos Elementos permitidos em s além dos dígitos
NumberStyles.None Apenas dígitos decimais.
NumberStyles.AllowDecimalPoint Os elementos . e fractional_digits. No entanto, fractional_digits deve consistir apenas em um ou mais dígitos 0 ou é lançado OverflowException .
NumberStyles.AllowExponent O s parâmetro também pode usar notação exponencial.
NumberStyles.AllowLeadingWhite O elemento ws no início de s.
NumberStyles.AllowTrailingWhite O elemento ws no final de s.
NumberStyles.AllowLeadingSign Um sinal pode aparecer antes dos dígitos.
NumberStyles.AllowTrailingSign Um sinal pode aparecer após os dígitos.
NumberStyles.AllowParentheses O elemento do signo na forma de parênteses que envolvem o valor numérico.
NumberStyles.AllowThousands O elemento ,
NumberStyles.AllowCurrencySymbol O $ elemento.

Se a NumberStyles.AllowHexSpecifier bandeira for usada, s deve ser a representação em cadeia de um valor hexadecimal sem prefixo. Por exemplo, "9AF3" analisa com sucesso, mas "0x9AF3" não. As únicas outras bandeiras que podem estar presentes em style e NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhite. (A NumberStyles enumeração tem um estilo numérico composto, NumberStyles.HexNumber, que inclui ambas as bandeiras de espaço em branco.)

O s parâmetro é analisado usando a informação de formatação num NumberFormatInfo objeto que é inicializado para a cultura do sistema atual. Para obter mais informações, veja NumberFormatInfo.CurrentInfo. Para analisar s usando a informação de formatação de uma cultura específica, chame o Int16.Parse(String, NumberStyles, IFormatProvider) método.

Ver também

Aplica-se a

Parse(String, IFormatProvider)

Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs

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

public:
 static short Parse(System::String ^ s, IFormatProvider ^ provider);
public:
 static short Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<short>::Parse;
public static short Parse(string s, IFormatProvider provider);
public static short Parse(string s, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> int16
Public Shared Function Parse (s As String, provider As IFormatProvider) As Short

Parâmetros

s
String

Uma cadeia contendo um número a converter.

provider
IFormatProvider

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

Devoluções

Um inteiro com sinal de 16 bits equivalente ao número especificado em s.

Implementações

Exceções

s não está no formato correto.

s representa um número menor que Int16.MinValue ou maior que Int16.MaxValue.

Exemplos

O exemplo seguinte analisa as representações das cadeias de Int16 valores com o Int16.Parse(String, IFormatProvider) método.

string stringToConvert;
short number;

stringToConvert = " 214 ";
try
{
   number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture);
   Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException)
{
   Console.WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException)
{
   Console.WriteLine("'{0'} is out of range of the Int16 data type.",
                     stringToConvert);
}

stringToConvert = " + 214";
try
{
   number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture);
   Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException)
{
   Console.WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException)
{
   Console.WriteLine("'{0'} is out of range of the Int16 data type.",
                     stringToConvert);
}

stringToConvert = " +214 ";
try
{
   number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture);
   Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException)
{
   Console.WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException)
{
   Console.WriteLine("'{0'} is out of range of the Int16 data type.",
                     stringToConvert);
}
// The example displays the following output to the console:
//       Converted ' 214 ' to 214.
//       Unable to parse ' + 214'.
//       Converted ' +214 ' to 214.
let stringToConvert = " 214 "
try
    let number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
    printfn $"Converted '{stringToConvert}' to {number}." 
with 
| :? FormatException ->
    printfn $"Unable to parse '{stringToConvert}'."
| :? OverflowException ->
    printfn $"'{stringToConvert}' is out of range of the Int16 data type."

let stringToConvert = " + 214"
try
    let number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
    printfn $"Converted '{stringToConvert}' to {number}." 
with 
| :? FormatException ->
    printfn $"Unable to parse '{stringToConvert}'."
| :? OverflowException -> 
    printfn $"'{stringToConvert}' is out of range of the Int16 data type."

let stringToConvert = " +214 "
try
    let number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
    printfn $"Converted '{stringToConvert}' to {number}." 
with
| :? FormatException ->
    printfn $"Unable to parse '{stringToConvert}'."
| :? OverflowException ->
    printfn $"'{stringToConvert}' is out of range of the Int16 data type."

// The example displays the following output to the console:
//       Converted ' 214 ' to 214.
//       Unable to parse ' + 214'.
//       Converted ' +214 ' to 214.
Dim stringToConvert As String
Dim number As Short

stringToConvert = " 214 "
Try
   number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
   Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
Catch e As FormatException
   Console.WriteLine("Unable to parse '{0}'.", stringToConvert)
Catch e As OverflowException
   Console.WriteLine("'{0'} is out of range of the Int16 data type.", _
                     stringToConvert)
End Try

stringToConvert = " + 214"                                 
Try
   number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
   Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
Catch e As FormatException
   Console.WriteLine("Unable to parse '{0}'.", stringToConvert)
Catch e As OverflowException
   Console.WriteLine("'{0'} is out of range of the Int16 data type.", _
                     stringToConvert)
End Try

stringToConvert = " +214 " 
Try
   number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
   Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
Catch e As FormatException
   Console.WriteLine("Unable to parse '{0}'.", stringToConvert)
Catch e As OverflowException
   Console.WriteLine("'{0'} is out of range of the Int16 data type.", _
                     stringToConvert)
End Try
' The example displays the following output to the console:
'       Converted ' 214 ' to 214.
'       Unable to parse ' + 214'.
'       Converted ' +214 ' to 214.

Observações

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

[ws][signo] dígitos[ws]

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

Elemento Descrição
ws Um espaço em branco opcional.
sign Um sinal opcional.
dígitos Uma sequência de dígitos que varia de 0 a 9.

O s parâmetro é interpretado usando o NumberStyles.Integer estilo. Além dos dígitos decimais, apenas espaços à frente e à frente juntamente com um sinal à esquerda são permitidos em s. 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 Int16.Parse(String, NumberStyles, IFormatProvider) método.

O provider parâmetro é uma IFormatProvider implementação que obtém um NumberFormatInfo objeto. Fornece NumberFormatInfo informação específica para cultura sobre o formato de s. Se provider for null, o NumberFormatInfo para a cultura atual é usado.

Ver também

Aplica-se a

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs

Analisa um intervalo de caracteres UTF-8 num valor.

public static short Parse(ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> int16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Short

Parâmetros

utf8Text
ReadOnlySpan<Byte>

A extensão de caracteres UTF-8 para analisar.

style
NumberStyles

Uma combinação bit a bit de estilos numéricos que pode estar presente em utf8Text.

provider
IFormatProvider

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

Devoluções

O resultado da análise sintática utf8Text.

Implementações

Aplica-se a

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs

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 com sinal de 16 bits.

public static short Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
public static short Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> int16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Short

Parâmetros

s
ReadOnlySpan<Char>

Um espaço que contém os caracteres que representam o número a converter.

style
NumberStyles

Uma combinação bit a bit de valores de enumeração que indica os elementos de estilo que podem estar presentes em s. Um valor típico a especificar é Integer.

provider
IFormatProvider

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

Devoluções

Um inteiro com sinal de 16 bits equivalente ao número especificado em s.

Implementações

Aplica-se a

Parse(String, NumberStyles, IFormatProvider)

Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs
Origem:
Int16.cs

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

public:
 static short Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
 static short Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<short>::Parse;
public static short Parse(string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static short Parse(string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> int16
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As Short

Parâmetros

s
String

Uma cadeia contendo um número a converter.

style
NumberStyles

Uma combinação bit a bit de valores de enumeração que indica os elementos de estilo que podem estar presentes em s. Um valor típico a especificar é Integer.

provider
IFormatProvider

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

Devoluções

Um inteiro com sinal de 16 bits equivalente ao número especificado em s.

Implementações

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 menor que Int16.MinValue ou maior que Int16.MaxValue.

-ou-

s inclui dígitos fracionários não nulos.

Exemplos

O exemplo seguinte utiliza uma variedade de parâmetros e styleprovider para analisar as representações das cadeias de Int16 valores.

string value;
short number;
NumberStyles style;
CultureInfo provider;

// Parse string using "." as the thousands separator
// and " " as the decimal separator.
value = "19 694,00";
style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
provider = new CultureInfo("fr-FR");

number = Int16.Parse(value, style, provider);
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
//    '19 694,00' converted to 19694.

try
{
   number = Int16.Parse(value, style, CultureInfo.InvariantCulture);
   Console.WriteLine("'{0}' converted to {1}.", value, number);
}
catch (FormatException)
{
   Console.WriteLine("Unable to parse '{0}'.", value);
}
// Displays:
//    Unable to parse '19 694,00'.

// Parse string using "$" as the currency symbol for en_GB and
// en-US cultures.
value = "$6,032.00";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
provider = new CultureInfo("en-GB");

try
{
   number = Int16.Parse(value, style, CultureInfo.InvariantCulture);
   Console.WriteLine("'{0}' converted to {1}.", value, number);
}
catch (FormatException)
{
   Console.WriteLine("Unable to parse '{0}'.", value);
}
// Displays:
//    Unable to parse '$6,032.00'.

provider = new CultureInfo("en-US");
number = Int16.Parse(value, style, provider);
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
//    '$6,032.00' converted to 6032.
// Parse string using "." as the thousands separator
// and " " as the decimal separator.
let value = "19 694,00"
let style = NumberStyles.AllowDecimalPoint ||| NumberStyles.AllowThousands
let provider = CultureInfo "fr-FR"

let number = Int16.Parse(value, style, provider)
printfn $"'{value}' converted to {number}." 
// Displays:
//    '19 694,00' converted to 19694.

try
    let number = Int16.Parse(value, style, CultureInfo.InvariantCulture)
    printfn $"'{value}' converted to {number}." 
with :? FormatException ->
    printfn $"Unable to parse '{value}'."
// Displays:
//    Unable to parse '19 694,00'.

// Parse string using "$" as the currency symbol for en_GB and
// en-US cultures.
let value = "$6,032.00"
let style = NumberStyles.Number ||| NumberStyles.AllowCurrencySymbol

try
    let number = Int16.Parse(value, style, CultureInfo.InvariantCulture)
    printfn $"'{value}' converted to {number}." 
with :? FormatException ->
    printfn $"Unable to parse '{value}'."
// Displays:
//    Unable to parse '$6,032.00'.

let provider = CultureInfo "en-US"
let number = Int16.Parse(value, style, provider)
printfn $"'{value}' converted to {number}."
// Displays:
//    '$6,032.00' converted to 6032.
Dim value As String
Dim number As Short
Dim style As NumberStyles
Dim provider As CultureInfo

' Parse string using "." as the thousands separator 
' and " " as the decimal separator.
value = "19 694,00"
style = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowThousands
provider = New CultureInfo("fr-FR")

number = Int16.Parse(value, style, provider)
Console.WriteLine("'{0}' converted to {1}.", value, number)
' Displays:
'    '19 694,00' converted to 19694.

Try
   number = Int16.Parse(value, style, CultureInfo.InvariantCulture)
   Console.WriteLine("'{0}' converted to {1}.", value, number)
Catch e As FormatException
   Console.WriteLine("Unable to parse '{0}'.", value)
End Try
' Displays:
'    Unable to parse '19 694,00'.

' Parse string using "$" as the currency symbol for en_GB and
' en-US cultures.
value = "$6,032.00"
style = NumberStyles.Number Or NumberStyles.AllowCurrencySymbol
provider = New CultureInfo("en-GB")

Try
   number = Int16.Parse(value, style, CultureInfo.InvariantCulture)
   Console.WriteLine("'{0}' converted to {1}.", value, number)
Catch e As FormatException
   Console.WriteLine("Unable to parse '{0}'.", value)
End Try
' Displays:
'    Unable to parse '$6,032.00'.
                        
provider = New CultureInfo("en-US")
number = Int16.Parse(value, style, provider)
Console.WriteLine("'{0}' converted to {1}.", value, number)
' Displays:
'    '$6,032.00' converted to 6032.

Observações

O style parâmetro define os elementos de estilo (como espaços em branco ou o sinal positivo) 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][$][sinal][dígitos,]dígitos[.fractional_digits][dígitos e[signos][ws]

Ou, se style incluir AllowHexSpecifier:

[ws]hexdigits[ws]

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

Elemento Descrição
ws Espaço em branco opcional. O espaço em branco pode aparecer no início de s se style inclui a NumberStyles.AllowLeadingWhite bandeira, ou no final de s se style inclui a NumberStyles.AllowTrailingWhite bandeira.
$ Um símbolo monetário específico de cada cultura. A sua posição na corda é definida pelas NumberFormatInfo.CurrencyPositivePattern propriedades e NumberFormatInfo.CurrencyNegativePattern da cultura atual. O símbolo monetário da cultura atual pode aparecer se sstyle incluir a NumberStyles.AllowCurrencySymbol bandeira.
assinar Um sinal opcional. O sinal pode aparecer no início de s se inclui a style bandeira, e pode aparecer no final de NumberStyles.AllowLeadingSign se s inclui a styleNumberStyles.AllowTrailingSign bandeira. Parênteses podem ser usados s para indicar um valor negativo se style incluir a NumberStyles.AllowParentheses bandeira.
dígitos Uma sequência de dígitos de 0 a 9.
, Um símbolo separador de milhares específico de cultura. O símbolo separador dos milhares da cultura atual pode aparecer se sstyle 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.
fractional_digits Uma sequência do dígito 0. Dígitos fracionários podem aparecer em s se style incluir a NumberStyles.AllowDecimalPoint bandeira. Se qualquer dígito diferente de 0 aparecer em fractional_digits, o método gera um OverflowException.
e O carácter 'e' ou 'E', que indica que s pode ser representado em notação exponencial. O s parâmetro pode representar um número em notação exponencial se style incluir a NumberStyles.AllowExponent bandeira. No entanto, o s parâmetro deve representar um número no intervalo do Int16 tipo de dado e não pode ter um componente fracionário diferente de zero.
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 sequência apenas com dígitos (que corresponde ao NumberStyles.None estilo) faz sempre pars com sucesso. A maioria dos membros restantes NumberStyles controla elementos que podem estar, mas não são obrigados a estar, nesta cadeia de entrada. A tabela seguinte indica como os membros individuais NumberStyles afetam os elementos que podem estar presentes em s.

Valores de NumberStyles não compostos Elementos permitidos em s além dos dígitos
NumberStyles.None Apenas dígitos decimais.
NumberStyles.AllowDecimalPoint Os elementos . e fractional_digits. No entanto, fractional_digits deve consistir apenas em um ou mais dígitos 0 ou é lançado OverflowException .
NumberStyles.AllowExponent O s parâmetro também pode usar notação exponencial.
NumberStyles.AllowLeadingWhite O elemento ws no início de s.
NumberStyles.AllowTrailingWhite O elemento ws no final de s.
NumberStyles.AllowLeadingSign Um sinal pode aparecer antes dos dígitos.
NumberStyles.AllowTrailingSign Um sinal pode aparecer após os dígitos.
NumberStyles.AllowParentheses O elemento do signo na forma de parênteses que envolvem o valor numérico.
NumberStyles.AllowThousands O elemento ,
NumberStyles.AllowCurrencySymbol O $ elemento.

Se a NumberStyles.AllowHexSpecifier bandeira for usada, s deve ser a representação em cadeia de um valor hexadecimal sem prefixo. Por exemplo, "9AF3" analisa com sucesso, mas "0x9AF3" não... As únicas outras bandeiras que podem estar presentes em style e NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhite. (A NumberStyles enumeração tem um estilo numérico composto, NumberStyles.HexNumber, que inclui ambas as bandeiras de espaço em branco.)

O provider parâmetro é uma IFormatProvider implementação cujo GetFormat método obtém um NumberFormatInfo objeto. O NumberFormatInfo objeto fornece informação específica da cultura sobre o formato de s. Se provider for null, o NumberFormatInfo objeto para a cultura atual é usado.

Ver também

Aplica-se a