Int16.Parse Metodo

Definizione

Converte la rappresentazione di stringa di un numero nell'equivalente intero con segno a 16 bit.

Overload

Parse(String, NumberStyles, IFormatProvider)

Converte la rappresentazione di stringa di un numero in uno stile specificato e in un formato specifico delle impostazioni cultura nell'equivalente intero con segno a 16 bit.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Converte la rappresentazione in forma di intervallo di un numero in uno stile specificato e in un formato specifico delle impostazioni cultura nell'equivalente intero con segno a 16 bit.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Analizza un intervallo di caratteri UTF-8 in un valore.

Parse(String, IFormatProvider)

Converte la rappresentazione di stringa di un numero in un formato specifico delle impostazioni cultura nell'equivalente intero con segno a 16 bit.

Parse(String)

Converte la rappresentazione di stringa di un numero nell'equivalente intero con segno a 16 bit.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analizza un intervallo di caratteri in un valore.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Analizza un intervallo di caratteri UTF-8 in un valore.

Parse(String, NumberStyles)

Converte la rappresentazione di stringa di un numero in uno stile specificato nell'equivalente intero con segno a 16 bit.

Parse(String, NumberStyles, IFormatProvider)

Converte la rappresentazione di stringa di un numero in uno stile specificato e in un formato specifico delle impostazioni cultura nell'equivalente intero con segno a 16 bit.

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

Parametri

s
String

Stringa che contiene un numero da convertire.

style
NumberStyles

Combinazione bit per bit dei valori di enumerazione che indica gli elementi di stile che possono essere presenti in s. Un valore tipico da specificare è Integer.

provider
IFormatProvider

Oggetto IFormatProvider che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a s.

Restituisce

Intero con segno a 16 bit equivalente al numero specificato in s.

Implementazioni

Eccezioni

style non è un valore di NumberStyles.

-oppure-

style non è una combinazione di valori di AllowHexSpecifier e HexNumber.

Il formato di s non è conforme a style.

s rappresenta un numero minore di Int16.MinValue o maggiore di Int16.MaxValue.

-oppure-

s include cifre frazionarie diverse da zero.

Esempio

Nell'esempio seguente viene usata un'ampia gamma di style parametri e provider per analizzare le rappresentazioni stringa dei Int16 valori.

String^ value;
Int16 number;
NumberStyles style;

// Parse string using "." as the thousands separator 
// and " " as the decimal separator.
value = "19 694,00";
style = NumberStyles::AllowDecimalPoint | NumberStyles::AllowThousands;
CultureInfo^ provider = gcnew 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 ^e)
{
   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 = gcnew CultureInfo("en-GB");

try
{
   number = Int16::Parse(value, style, CultureInfo::InvariantCulture);
   Console::WriteLine("'{0}' converted to {1}.", value, number);
}
catch (FormatException ^e)
{
   Console::WriteLine("Unable to parse '{0}'.", value);
}
// Displays:
//    Unable to parse '$6,032.00'.
                        
provider = gcnew CultureInfo("en-US");
number = Int16::Parse(value, style, provider);
Console::WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
//    '$6,032.00' converted to 6032.
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.

Commenti

Il style parametro definisce gli elementi di stile , ad esempio spazio vuoto o segno positivo, consentiti nel s parametro per l'esito positivo dell'operazione di analisi. Deve essere una combinazione di flag di bit dall'enumerazione NumberStyles . A seconda del valore di style, il s parametro può includere gli elementi seguenti:

[ws] [$] [sign] [cifre,]cifre[.fractional_digits][e[sign]digits][ws]

In alternativa, se style include AllowHexSpecifier:

[ws]hexdigits[ws]

Gli elementi tra parentesi quadre ([e]) sono facoltativi. La tabella seguente descrive i singoli elementi.

Elemento Descrizione
ws Spazio vuoto facoltativo. Lo spazio vuoto può essere visualizzato all'inizio di s se include il NumberStyles.AllowLeadingWhite flag o alla fine di s se style include il NumberStyles.AllowTrailingWhite flag.style
$ Simbolo di valuta specifico delle impostazioni cultura. La posizione nella stringa è definita dalla NumberFormatInfo.CurrencyPositivePattern proprietà e NumberFormatInfo.CurrencyNegativePattern delle impostazioni cultura correnti. Il simbolo di valuta della cultura corrente può essere visualizzato in s se style include il NumberStyles.AllowCurrencySymbol flag.
sign Segno facoltativo. Il segno può essere visualizzato all'inizio di s se include il NumberStyles.AllowLeadingSign flag e può essere visualizzato alla fine di s se style include il NumberStyles.AllowTrailingSignstyle flag. Le parentesi possono essere usate in s per indicare un valore negativo se style include il NumberStyles.AllowParentheses flag.
Cifre Sequenza di cifre da 0 a 9.
, Simbolo separatore specifico delle impostazioni cultura. Il simbolo separatore delle migliaia di impostazioni cultura correnti può essere visualizzato se sstyle include il NumberStyles.AllowThousands flag.
. Simbolo decimale specifico delle impostazioni cultura. Il simbolo decimale della cultura corrente può essere visualizzato in s se style include il NumberStyles.AllowDecimalPoint flag.
Cifre_frazionarie Sequenza della cifra 0. Le cifre frazionarie possono essere visualizzate in s se style include il NumberStyles.AllowDecimalPoint flag. Se una cifra diversa da 0 viene visualizzata in fractional_digits, il metodo genera un OverflowExceptionoggetto .
e Carattere 'e' o 'E', che indica che s può essere rappresentato nella notazione esponenziale. Il s parametro può rappresentare un numero in notazione esponenziale se style include il NumberStyles.AllowExponent flag. Tuttavia, il s parametro deve rappresentare un numero nell'intervallo Int16 del tipo di dati e non può avere un componente frazionaria diverso da zero.
hexdigits Sequenza di cifre esadecimali da 0 a f o da 0 a F.

Nota

Tutti i caratteri NUL terminanti (U+0000) vengono s ignorati dall'operazione di analisi, indipendentemente dal valore dell'argomento style .

Stringa con cifre solo (che corrisponde allo NumberStyles.None stile) analizza sempre correttamente. La maggior parte degli elementi di controllo dei membri rimanenti NumberStyles che possono essere ma non sono necessari per essere presenti in questa stringa di input. La tabella seguente indica come i singoli NumberStyles membri influiscono sugli elementi che possono essere presenti in s.

Valori NumberStyles non compositi Elementi consentiti in s oltre alle cifre
NumberStyles.None Solo cifre decimali.
NumberStyles.AllowDecimalPoint Elementi . e fractional_digits . Tuttavia, fractional_digits deve essere costituito da una o più cifre 0 o viene generata un'eccezione OverflowException .
NumberStyles.AllowExponent Il s parametro può anche usare la notazione esponenziale.
NumberStyles.AllowLeadingWhite Elemento ws all'inizio di s.
NumberStyles.AllowTrailingWhite Elemento ws alla fine di s.
NumberStyles.AllowLeadingSign Un segno può essere visualizzato prima delle cifre.
NumberStyles.AllowTrailingSign Un segno può essere visualizzato dopo le cifre.
NumberStyles.AllowParentheses Elemento di segno sotto forma di parentesi che racchiude il valore numerico.
NumberStyles.AllowThousands Elemento , .
NumberStyles.AllowCurrencySymbol Elemento $.

Se viene usato il NumberStyles.AllowHexSpecifier flag, s deve essere la rappresentazione stringa di un valore esadecimale senza prefisso. Ad esempio, "9AF3" analizza correttamente, ma "0x9AF3" non.. Gli unici flag che possono essere presenti in style sono NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. L'enumerazione NumberStyles ha uno stile numero composito, , NumberStyles.HexNumberche include entrambi i flag di spazi vuoti.

Il provider parametro è un'implementazione IFormatProvider il cui GetFormat metodo ottiene un NumberFormatInfo oggetto. L'oggetto NumberFormatInfo fornisce informazioni specifiche delle impostazioni cultura sul formato di s. Se provider è null, viene usato l'oggetto NumberFormatInfo per le impostazioni cultura correnti.

Vedi anche

Si applica a

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Converte la rappresentazione in forma di intervallo di un numero in uno stile specificato e in un formato specifico delle impostazioni cultura nell'equivalente intero con segno a 16 bit.

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

Parametri

s
ReadOnlySpan<Char>

Intervallo contenente i caratteri che rappresentano il numero da convertire.

style
NumberStyles

Combinazione bit per bit dei valori di enumerazione che indica gli elementi di stile che possono essere presenti in s. Un valore tipico da specificare è Integer.

provider
IFormatProvider

Oggetto IFormatProvider che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a s.

Restituisce

Intero con segno a 16 bit equivalente al numero specificato in s.

Implementazioni

Si applica a

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Analizza un intervallo di caratteri UTF-8 in un valore.

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

Parametri

utf8Text
ReadOnlySpan<Byte>

Intervallo di caratteri UTF-8 da analizzare.

style
NumberStyles

Combinazione bit per bit di stili numerici che possono essere presenti in utf8Text.

provider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a utf8Text.

Restituisce

Risultato dell'analisi utf8Textdi .

Implementazioni

Si applica a

Parse(String, IFormatProvider)

Converte la rappresentazione di stringa di un numero in un formato specifico delle impostazioni cultura nell'equivalente intero con segno a 16 bit.

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

Parametri

s
String

Stringa che contiene un numero da convertire.

provider
IFormatProvider

Oggetto IFormatProvider che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a s.

Restituisce

Intero con segno a 16 bit equivalente al numero specificato in s.

Implementazioni

Eccezioni

Il formato di s non è corretto.

s rappresenta un numero minore di Int16.MinValue o maggiore di Int16.MaxValue.

Esempio

Nell'esempio seguente vengono analizzate le rappresentazioni di stringa dei Int16 valori con il Int16.Parse(String, IFormatProvider) metodo .

String^ stringToConvert;
Int16 number;

stringToConvert = " 214 ";
try
{
   number = Int16::Parse(stringToConvert, CultureInfo::InvariantCulture);
   Console::WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException ^e)
{
   Console::WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException ^e)
{
   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 ^e)
{
   Console::WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException ^e)
{
   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 ^e)
{
   Console::WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException ^e)
{
   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.
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.

Commenti

Il s parametro contiene un numero di form:

[ws] [sign]digits[ws]

Gli elementi tra parentesi quadre ([e]) sono facoltativi. La tabella seguente descrive i singoli elementi.

Elemento Descrizione
ws Spazio vuoto facoltativo.
segno Segno facoltativo.
Cifre Sequenza di cifre compresa tra 0 e 9.

Il s parametro viene interpretato usando lo NumberStyles.Integer stile . Oltre alle cifre decimali, solo gli spazi iniziali e finali insieme a un segno iniziale sono consentiti in s. Per definire in modo esplicito gli elementi di stile insieme alle informazioni di formattazione specifiche delle impostazioni cultura che possono essere presenti in s, usare il Int16.Parse(String, NumberStyles, IFormatProvider) metodo .

Il provider parametro è un'implementazione IFormatProvider che ottiene un NumberFormatInfo oggetto . fornisce NumberFormatInfo informazioni specifiche delle impostazioni cultura sul formato di s. Se provider è null, viene utilizzato per NumberFormatInfo le impostazioni cultura correnti.

Vedi anche

Si applica a

Parse(String)

Converte la rappresentazione di stringa di un numero nell'equivalente intero con segno a 16 bit.

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

Parametri

s
String

Stringa che contiene un numero da convertire.

Restituisce

Intero con segno a 16 bit equivalente al numero contenuto in s.

Eccezioni

Il formato di s non è corretto.

s rappresenta un numero minore di Int16.MinValue o maggiore di Int16.MaxValue.

Esempio

Nell'esempio seguente viene illustrato come convertire un valore stringa in un valore intero con segno a 16 bit usando il Int16.Parse(String) metodo . Il valore intero risultante viene quindi visualizzato nella console.

String^ value;
Int16 number;
   
value = " 12603 ";
try
{
   number = Int16::Parse(value);
   Console::WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException ^e)
{
   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 ^e)
{
   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 ^e)
{
   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.
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.

Commenti

Il s parametro contiene un numero di form:

[ws] [sign]digits[ws]

Gli elementi tra parentesi quadre ([e]) sono facoltativi. La tabella seguente descrive i singoli elementi.

Elemento Descrizione
ws Spazio vuoto facoltativo.
sign Segno facoltativo.
Cifre Sequenza di cifre compresa tra 0 e 9.

Il s parametro viene interpretato usando lo NumberStyles.Integer stile . Oltre alle cifre decimali del valore intero, sono consentiti solo spazi iniziali e finali insieme a un segno iniziale. Per definire in modo esplicito gli elementi di stile che possono essere presenti in s, usare il Int16.Parse(String, NumberStyles) metodo o Parse .

Il s parametro viene analizzato usando le informazioni di formattazione in un NumberFormatInfo oggetto inizializzato per le impostazioni cultura di sistema correnti. Per altre informazioni, vedere CurrentInfo. Per analizzare una stringa usando le informazioni di formattazione di altre impostazioni cultura, usare il Int16.Parse(String, IFormatProvider) metodo o Int16.Parse(String, NumberStyles, IFormatProvider) .

Vedi anche

Si applica a

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analizza un intervallo di caratteri in un valore.

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

Parametri

s
ReadOnlySpan<Char>

Intervallo di caratteri da analizzare.

provider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a s.

Restituisce

Risultato dell'analisi sdi .

Implementazioni

Si applica a

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Analizza un intervallo di caratteri UTF-8 in un valore.

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

Parametri

utf8Text
ReadOnlySpan<Byte>

Intervallo di caratteri UTF-8 da analizzare.

provider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a utf8Text.

Restituisce

Risultato dell'analisi utf8Textdi .

Implementazioni

Si applica a

Parse(String, NumberStyles)

Converte la rappresentazione di stringa di un numero in uno stile specificato nell'equivalente intero con segno a 16 bit.

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

Parametri

s
String

Stringa che contiene un numero da convertire.

style
NumberStyles

Combinazione bit per bit dei valori di enumerazione che indica gli elementi di stile che possono essere presenti in s. Un valore tipico da specificare è Integer.

Restituisce

Intero con segno a 16 bit equivalente al numero specificato in s.

Eccezioni

style non è un valore di NumberStyles.

-oppure-

style non è una combinazione di valori di AllowHexSpecifier e HexNumber.

Il formato di s non è conforme a style.

s rappresenta un numero minore di Int16.MinValue o maggiore di Int16.MaxValue.

-oppure-

s include cifre frazionarie diverse da zero.

Esempio

Nell'esempio seguente viene usato il Int16.Parse(String, NumberStyles) metodo per analizzare le rappresentazioni di stringa dei Int16 valori usando le impostazioni cultura en-US.

using namespace System;
using namespace System::Globalization;

ref 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;
      ParseSample::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
      {
         Int16 number = Int16::Parse(value, style);
         Console::WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException ^e)
      {
         Console::WriteLine("Unable to parse '{0}' with style {1}.", value, 
                            style);
      }
      catch (OverflowException ^e)
      {
         Console::WriteLine("'{0}' is out of range of the Int16 type.", value);
      }
   }
};

int main()
{
    ParseSample::Main();
    Console::ReadLine();
    return 0;
}
// The example displays the following output:
//       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.
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.

Commenti

Il style parametro definisce gli elementi di stile(ad esempio uno spazio vuoto o un simbolo di segno) consentiti nel s parametro per l'esito positivo dell'operazione di analisi. Deve essere una combinazione di flag di bit dell'enumerazione NumberStyles . A seconda del valore di style, il s parametro può includere gli elementi seguenti:

[ws] [$] [sign] [digits,]digits[.fractional_digits][e[sign]digits][ws]

In alternativa, se style include AllowHexSpecifier:

[ws]hexdigits[ws]

Gli elementi tra parentesi quadre ([ e ]) sono facoltativi. La tabella seguente descrive i singoli elementi.

Elemento Descrizione
ws Spazio vuoto facoltativo. Lo spazio vuoto può essere visualizzato all'inizio di s se include il NumberStyles.AllowLeadingWhite flag o alla fine di s se style include il NumberStyles.AllowTrailingWhite flag .style
$ Simbolo di valuta specifico delle impostazioni cultura. La posizione nella stringa è definita dalla NumberFormatInfo.CurrencyPositivePattern proprietà e NumberFormatInfo.CurrencyNegativePattern delle impostazioni cultura correnti. Il simbolo di valuta delle impostazioni cultura correnti può essere visualizzato in s se style include il NumberStyles.AllowCurrencySymbol flag .
sign Segno facoltativo. Il segno può essere visualizzato all'inizio di s se include il NumberStyles.AllowLeadingSign flag e può essere visualizzato alla fine di s se style include il NumberStyles.AllowTrailingSignstyle flag . Le parentesi possono essere usate in s per indicare un valore negativo se style include il NumberStyles.AllowParentheses flag.
Cifre Sequenza di cifre da 0 a 9.
, Simbolo separatore specifico delle impostazioni cultura. Il simbolo separatore delle migliaia di impostazioni cultura correnti può essere visualizzato se sstyle include il NumberStyles.AllowThousands flag.
. Simbolo decimale specifico delle impostazioni cultura. Il simbolo decimale della cultura corrente può essere visualizzato in s se style include il NumberStyles.AllowDecimalPoint flag.
Cifre_frazionarie Sequenza della cifra 0. Le cifre frazionarie possono essere visualizzate in s se style include il NumberStyles.AllowDecimalPoint flag. Se una cifra diversa da 0 viene visualizzata in fractional_digits, il metodo genera un OverflowExceptionoggetto .
e Carattere 'e' o 'E', che indica che s può essere rappresentato nella notazione esponenziale. Il s parametro può rappresentare un numero in notazione esponenziale se style include il NumberStyles.AllowExponent flag. Tuttavia, il s parametro deve rappresentare un numero nell'intervallo Int16 del tipo di dati e non può avere un componente frazionaria diverso da zero.
hexdigits Sequenza di cifre esadecimali da 0 a f o da 0 a F.

Nota

Tutti i caratteri NUL terminanti (U+0000) vengono s ignorati dall'operazione di analisi, indipendentemente dal valore dell'argomento style .

Stringa con cifre solo (che corrisponde allo NumberStyles.None stile) analizza sempre correttamente. La maggior parte degli elementi di controllo dei membri rimanenti NumberStyles che possono essere ma non sono necessari per essere presenti in questa stringa di input. La tabella seguente indica come i singoli NumberStyles membri influiscono sugli elementi che possono essere presenti in s.

Valori NumberStyles non compositi Elementi consentiti in s oltre alle cifre
NumberStyles.None Solo cifre decimali.
NumberStyles.AllowDecimalPoint Elementi . e fractional_digits . Tuttavia, fractional_digits deve essere costituito da una o più cifre 0 o viene generata un'eccezione OverflowException .
NumberStyles.AllowExponent Il s parametro può anche usare la notazione esponenziale.
NumberStyles.AllowLeadingWhite Elemento ws all'inizio di s.
NumberStyles.AllowTrailingWhite Elemento ws alla fine di s.
NumberStyles.AllowLeadingSign Un segno può essere visualizzato prima delle cifre.
NumberStyles.AllowTrailingSign Un segno può essere visualizzato dopo le cifre.
NumberStyles.AllowParentheses Elemento di segno sotto forma di parentesi che racchiude il valore numerico.
NumberStyles.AllowThousands Elemento , .
NumberStyles.AllowCurrencySymbol Elemento $.

Se viene usato il NumberStyles.AllowHexSpecifier flag, s deve essere la rappresentazione stringa di un valore esadecimale senza prefisso. Ad esempio, "9AF3" analizza correttamente, ma "0x9AF3" non. Gli unici flag che possono essere presenti in style sono NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. L'enumerazione NumberStyles ha uno stile numero composito, , NumberStyles.HexNumberche include entrambi i flag di spazi vuoti.

Il s parametro viene analizzato usando le informazioni di formattazione in un NumberFormatInfo oggetto inizializzato per le impostazioni cultura di sistema correnti. Per altre informazioni, vedere NumberFormatInfo.CurrentInfo. Per analizzare usando le informazioni di formattazione s di una cultura specifica, chiamare il Int16.Parse(String, NumberStyles, IFormatProvider) metodo .

Vedi anche

Si applica a