Int32.Parse Metodo

Definizione

Converte la rappresentazione di stringa di un numero nell'equivalente intero con segno a 32 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 32 bit.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Converte la rappresentazione in forma di intervallo di un numero in uno stile e in un formato specifico delle impostazioni cultura specificati nell'equivalente intero con segno a 32 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 32 bit.

Parse(String)

Converte la rappresentazione di stringa di un numero nell'equivalente intero con segno a 32 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 32 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 32 bit.

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

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 che fornisce informazioni specifiche delle impostazioni cultura relative al formato di s.

Restituisce

Intero con segno a 32 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 Int32.MinValue o maggiore di Int32.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 Int32 valori. Illustra anche alcuni dei diversi modi in cui la stessa stringa può essere interpretata a seconda delle impostazioni cultura le cui informazioni di formattazione vengono usate per l'operazione di analisi.

using namespace System;
using namespace System::Globalization;

public ref class ParseInt32
{
public:
   static void Main()
   {
      Convert("12,000", NumberStyles::Float | NumberStyles::AllowThousands, 
              gcnew CultureInfo("en-GB"));
      Convert("12,000", NumberStyles::Float | NumberStyles::AllowThousands,
              gcnew CultureInfo("fr-FR"));
      Convert("12,000", NumberStyles::Float, gcnew CultureInfo("en-US"));

      Convert("12 425,00", NumberStyles::Float | NumberStyles::AllowThousands,
              gcnew CultureInfo("sv-SE"));
      Convert("12,425.00", NumberStyles::Float | NumberStyles::AllowThousands,
              NumberFormatInfo::InvariantInfo);
      Convert("631,900", NumberStyles::Integer | NumberStyles::AllowDecimalPoint, 
              gcnew CultureInfo("fr-FR"));
      Convert("631,900", NumberStyles::Integer | NumberStyles::AllowDecimalPoint,
              gcnew CultureInfo("en-US"));
      Convert("631,900", NumberStyles::Integer | NumberStyles::AllowThousands,
              gcnew CultureInfo("en-US"));
   }

private:
   static void Convert(String^ value, NumberStyles style,
                               IFormatProvider^ provider)
   {
      try
      {
         int number = Int32::Parse(value, style, provider);
         Console::WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException^)
      {
         Console::WriteLine("Unable to convert '{0}'.", value);
      }
      catch (OverflowException^)
      {
         Console::WriteLine("'{0}' is out of range of the Int32 type.", value);   
      }
   }                               
};

int main()
{
    ParseInt32::Main();
}
// This example displays the following output to the console:
//       Converted '12,000' to 12000.
//       Converted '12,000' to 12.
//       Unable to convert '12,000'.
//       Converted '12 425,00' to 12425.
//       Converted '12,425.00' to 12425.
//       '631,900' is out of range of the Int32 type.
//       Unable to convert '631,900'.
//       Converted '631,900' to 631900.
using System;
using System.Globalization;

public class ParseInt32
{
   public static void Main()
   {
      Convert("12,000", NumberStyles.Float | NumberStyles.AllowThousands,
              new CultureInfo("en-GB"));
      Convert("12,000", NumberStyles.Float | NumberStyles.AllowThousands,
              new CultureInfo("fr-FR"));
      Convert("12,000", NumberStyles.Float, new CultureInfo("en-US"));

      Convert("12 425,00", NumberStyles.Float | NumberStyles.AllowThousands,
              new CultureInfo("sv-SE"));
      Convert("12,425.00", NumberStyles.Float | NumberStyles.AllowThousands,
              NumberFormatInfo.InvariantInfo);
      Convert("631,900", NumberStyles.Integer | NumberStyles.AllowDecimalPoint,
              new CultureInfo("fr-FR"));
      Convert("631,900", NumberStyles.Integer | NumberStyles.AllowDecimalPoint,
              new CultureInfo("en-US"));
      Convert("631,900", NumberStyles.Integer | NumberStyles.AllowThousands,
              new CultureInfo("en-US"));
   }

   private static void Convert(string value, NumberStyles style,
                               IFormatProvider provider)
   {
      try
      {
         int number = Int32.Parse(value, style, provider);
         Console.WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException)
      {
         Console.WriteLine("Unable to convert '{0}'.", value);
      }
      catch (OverflowException)
      {
         Console.WriteLine("'{0}' is out of range of the Int32 type.", value);
      }
   }
}
// This example displays the following output to the console:
//       Converted '12,000' to 12000.
//       Converted '12,000' to 12.
//       Unable to convert '12,000'.
//       Converted '12 425,00' to 12425.
//       Converted '12,425.00' to 12425.
//       '631,900' is out of range of the Int32 type.
//       Unable to convert '631,900'.
//       Converted '631,900' to 631900.
open System
open System.Globalization

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

convert "12,000" (NumberStyles.Float ||| NumberStyles.AllowThousands) (CultureInfo "en-GB")
convert "12,000" (NumberStyles.Float ||| NumberStyles.AllowThousands) (CultureInfo "fr-FR")
convert "12,000" NumberStyles.Float (CultureInfo "en-US")
convert "12 425,00" (NumberStyles.Float ||| NumberStyles.AllowThousands) (CultureInfo "sv-SE")
convert "12,425.00" (NumberStyles.Float ||| NumberStyles.AllowThousands) NumberFormatInfo.InvariantInfo
convert "631,900" (NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint) (CultureInfo "fr-FR")
convert "631,900" (NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint) (CultureInfo "en-US")
convert "631,900" (NumberStyles.Integer ||| NumberStyles.AllowThousands) (CultureInfo "en-US")

// This example displays the following output to the console:
//       Converted '12,000' to 12000.
//       Converted '12,000' to 12.
//       Unable to convert '12,000'.
//       Converted '12 425,00' to 12425.
//       Converted '12,425.00' to 12425.
//       '631,900' is out of range of the Int32 type.
//       Unable to convert '631,900'.
//       Converted '631,900' to 631900.
Imports System.Globalization

Module ParseInt32
   Public Sub Main()
      Convert("12,000", NumberStyles.Float Or NumberStyles.AllowThousands, _
              New CultureInfo("en-GB"))      
      Convert("12,000", NumberStyles.Float Or NumberStyles.AllowThousands, _
              New CultureInfo("fr-FR"))
      Convert("12,000", NumberStyles.Float, New CultureInfo("en-US"))
      
      Convert("12 425,00", NumberStyles.Float Or NumberStyles.AllowThousands, _
              New CultureInfo("sv-SE")) 
      Convert("12,425.00", NumberStyles.Float Or NumberStyles.AllowThousands, _
              NumberFormatInfo.InvariantInfo) 
      Convert("631,900", NumberStyles.Integer Or NumberStyles.AllowDecimalPoint, _ 
              New CultureInfo("fr-FR"))
      Convert("631,900", NumberStyles.Integer Or NumberStyles.AllowDecimalPoint, _
              New CultureInfo("en-US"))
      Convert("631,900", NumberStyles.Integer Or NumberStyles.AllowThousands, _
              New CultureInfo("en-US"))
   End Sub

   Private Sub Convert(value As String, style As NumberStyles, _
                       provider As IFormatProvider)
      Try
         Dim number As Integer = Int32.Parse(value, style, provider)
         Console.WriteLine("Converted '{0}' to {1}.", value, number)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", value)
      Catch e As OverflowException
         Console.WriteLine("'{0}' is out of range of the Int32 type.", value)   
      End Try
   End Sub                       
End Module
' This example displays the following output to the console:
'       Converted '12,000' to 12000.
'       Converted '12,000' to 12.
'       Unable to convert '12,000'.
'       Converted '12 425,00' to 12425.
'       Converted '12,425.00' to 12425.
'       '631,900' is out of range of the Int32 type.
'       Unable to convert '631,900'.
'       Converted '631,900' to 631900.

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_digist][e[sign]exponential_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 e può essere visualizzato alla fine di s se style include il NumberStyles.AllowTrailingWhite flag.style
$ Simbolo di valuta specifico delle impostazioni cultura. La sua posizione nella stringa è definita dalla NumberFormatInfo.CurrencyPositivePattern proprietà dell'oggetto NumberFormatInfo restituito dal GetFormat metodo del provider parametro. Il simbolo di valuta 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 o alla fine di s se style include il NumberStyles.AllowTrailingSign flag.style Le parentesi possono essere usate in s per indicare un valore negativo se style include il NumberStyles.AllowParentheses flag.
Cifre

Cifre_frazionarie

exponential_digits
Sequenza di cifre da 0 a 9. Per fractional_digits, solo la cifra 0 è valida.
, Simbolo separatore specifico delle impostazioni cultura. Il separatore migliaia di impostazioni cultura specificate da provider può essere visualizzato in s se style include il NumberStyles.AllowThousands flag.
. Simbolo decimale specifico delle impostazioni cultura. Il simbolo decimale delle impostazioni cultura specificate da provider può essere visualizzato in s se style include il NumberStyles.AllowDecimalPoint flag.

Solo la cifra 0 può essere visualizzata come cifra frazionaria per l'esito positivo dell'operazione di analisi; se fractional_digits include qualsiasi altra cifra, viene generata un'eccezione OverflowException .
e Carattere 'e' o 'E', che indica che il valore è rappresentato nella notazione esponenziale. Il s parametro può rappresentare un numero in notazione esponenziale se style include il NumberStyles.AllowExponent flag.
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 .

Una stringa con cifre decimali (che corrisponde allo NumberStyles.None stile) analizza sempre correttamente se si trova nell'intervallo del Int32 tipo. 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 decimali ( . ) e cifre frazionarie . Tuttavia, le cifre frazionarie devono essere costituite da una o più cifre 0 o viene generata.OverflowException
NumberStyles.AllowExponent Il s parametro può anche usare la notazione esponenziale. Se s rappresenta un numero in notazione esponenziale, deve rappresentare un intero all'interno dell'intervallo del tipo di Int32 dati senza un componente frazionaria diverso da zero.
NumberStyles.AllowLeadingWhite Elemento ws all'inizio di s.
NumberStyles.AllowTrailingWhite Elemento ws alla fine di s.
NumberStyles.AllowLeadingSign Un segno positivo può essere visualizzato prima delle cifre.
NumberStyles.AllowTrailingSign Un segno positivo può essere visualizzato dopo le cifre.
NumberStyles.AllowParentheses Elemento di segno sotto forma di parentesi che racchiude il valore numerico.
NumberStyles.AllowThousands Elemento separatore migliaia ( , ).
NumberStyles.AllowCurrencySymbol Elemento $.

Se viene usato il NumberStyles.AllowHexSpecifier flag, s deve essere un valore esadecimale senza prefisso. Ad esempio, "C9AF3" analizza correttamente, ma "0xC9AF3" non viene eseguito. 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 , ad esempio un NumberFormatInfo oggetto o CultureInfo . Il provider parametro fornisce informazioni specifiche delle impostazioni cultura usate nell'analisi. 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 e in un formato specifico delle impostazioni cultura specificati nell'equivalente intero con segno a 32 bit.

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

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 che fornisce informazioni specifiche delle impostazioni cultura relative al formato di s.

Restituisce

Intero con segno a 32 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 int Parse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> int
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Integer

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 32 bit.

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

Parametri

s
String

Stringa che contiene un numero da convertire.

provider
IFormatProvider

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

Restituisce

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

Implementazioni

Eccezioni

s non è nel formato corretto.

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

Esempio

L'esempio seguente è il gestore eventi click del pulsante di un modulo Web. Usa la matrice restituita dalla HttpRequest.UserLanguages proprietà per determinare le impostazioni locali dell'utente. Crea quindi un'istanza di un CultureInfo oggetto che corrisponde a tali impostazioni locali. L'oggetto NumberFormatInfo appartenente a tale CultureInfo oggetto viene quindi passato al Parse(String, IFormatProvider) metodo per convertire l'input dell'utente in un Int32 valore.

protected void OkToInteger_Click(object sender, EventArgs e)
{
    string locale;
    int number;
    CultureInfo culture;

    // Return if string is empty
    if (String.IsNullOrEmpty(this.inputNumber.Text))
        return;

    // Get locale of web request to determine possible format of number
    if (Request.UserLanguages.Length == 0)
        return;
    locale = Request.UserLanguages[0];
    if (String.IsNullOrEmpty(locale))
        return;

    // Instantiate CultureInfo object for the user's locale
    culture = new CultureInfo(locale);

    // Convert user input from a string to a number
    try
    {
        number = Int32.Parse(this.inputNumber.Text, culture.NumberFormat);
    }
    catch (FormatException)
    {
        return;
    }
    catch (Exception)
    {
        return;
    }
    // Output number to label on web form
    this.outputNumber.Text = "Number is " + number.ToString();
}
Protected Sub OkToInteger_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OkToInteger.Click
   Dim locale As String
   Dim culture As CultureInfo
   Dim number As Integer

   ' Return if string is empty
   If String.IsNullOrEmpty(Me.inputNumber.Text) Then Exit Sub

   ' Get locale of web request to determine possible format of number
   If Request.UserLanguages.Length = 0 Then Exit Sub
   locale = Request.UserLanguages(0)
   If String.IsNullOrEmpty(locale) Then Exit Sub

   ' Instantiate CultureInfo object for the user's locale
   culture = New CultureInfo(locale)

   ' Convert user input from a string to a number
   Try
      number = Int32.Parse(Me.inputNumber.Text, culture.NumberFormat)
   Catch ex As FormatException
      Exit Sub
   Catch ex As Exception
      Exit Sub
   End Try

   ' Output number to label on web form
   Me.outputNumber.Text = "Number is " & number.ToString()
End Sub

Commenti

Questo overload del Parse(String, IFormatProvider) metodo viene in genere usato per convertire il testo che può essere formattato in diversi modi in un Int32 valore. Ad esempio, può essere usato per convertire il testo immesso da un utente in una casella di testo HTML in un valore numerico.

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, 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 Int32.Parse(String, NumberStyles, IFormatProvider) metodo .

Il provider parametro è un'implementazione IFormatProvider , ad esempio un NumberFormatInfo oggetto o CultureInfo . Il provider parametro fornisce informazioni specifiche delle impostazioni cultura sul formato di s. Se provider è null, viene utilizzato l'oggetto NumberFormatInfo per 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 32 bit.

public:
 static int Parse(System::String ^ s);
public static int Parse (string s);
static member Parse : string -> int
Public Shared Function Parse (s As String) As Integer

Parametri

s
String

Stringa che contiene un numero da convertire.

Restituisce

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

Eccezioni

Il formato di s non è corretto.

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

Esempio

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

using namespace System;

void main()
{
   array<String^>^ values = { "+13230", "-0", "1,390,146", "$190,235,421,127",
                              "0xFA1B", "163042", "-10", "007", "2147483647", 
                              "2147483648", "16e07", "134985.0", "-12034",
                              "-2147483648", "-2147483649" };
   for each (String^ value in values)
   {
      try {
         Int32 number = Int32::Parse(value); 
         Console::WriteLine("{0} --> {1}", value, number);
      }
      catch (FormatException^ e) {
         Console::WriteLine("{0}: Bad Format", value);
      }   
      catch (OverflowException^ e) {
         Console::WriteLine("{0}: Overflow", value);   
      }  
   }
}
// The example displays the following output:
//       +13230 --> 13230
//       -0 --> 0
//       1,390,146: Bad Format
//       $190,235,421,127: Bad Format
//       0xFA1B: Bad Format
//       163042 --> 163042
//       -10 --> -10
//       007 --> 7
//       2147483647 --> 2147483647
//       2147483648: Overflow
//       16e07: Bad Format
//       134985.0: Bad Format
//       -12034 --> -12034
//       -2147483648 --> -2147483648
//       -2147483649: Overflow
using System;

public class Example
{
   public static void Main()
   {
      string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127",
                          "0xFA1B", "163042", "-10", "007", "2147483647",
                          "2147483648", "16e07", "134985.0", "-12034",
                          "-2147483648", "-2147483649" };
      foreach (string value in values)
      {
         try {
            int number = Int32.Parse(value);
            Console.WriteLine("{0} --> {1}", value, number);
         }
         catch (FormatException) {
            Console.WriteLine("{0}: Bad Format", value);
         }
         catch (OverflowException) {
            Console.WriteLine("{0}: Overflow", value);
         }
      }
   }
}
// The example displays the following output:
//       +13230 --> 13230
//       -0 --> 0
//       1,390,146: Bad Format
//       $190,235,421,127: Bad Format
//       0xFA1B: Bad Format
//       163042 --> 163042
//       -10 --> -10
//       007 --> 7
//       2147483647 --> 2147483647
//       2147483648: Overflow
//       16e07: Bad Format
//       134985.0: Bad Format
//       -12034 --> -12034
//       -2147483648 --> -2147483648
//       -2147483649: Overflow
open System

let values =
    [ "+13230"; "-0"; "1,390,146"; "$190,235,421,127"
      "0xFA1B"; "163042"; "-10"; "007"; "2147483647"
      "2147483648"; "16e07"; "134985.0"; "-12034"
      "-2147483648"; "-2147483649" ]

for value in values do
    try
        let number = Int32.Parse value
        printfn $"{value} --> {number}"
    with 
    | :? FormatException ->
        printfn $"{value}: Bad Format"
    | :? OverflowException ->
        printfn $"{value}: Overflow"
    

// The example displays the following output:
//       +13230 --> 13230
//       -0 --> 0
//       1,390,146: Bad Format
//       $190,235,421,127: Bad Format
//       0xFA1B: Bad Format
//       163042 --> 163042
//       -10 --> -10
//       007 --> 7
//       2147483647 --> 2147483647
//       2147483648: Overflow
//       16e07: Bad Format
//       134985.0: Bad Format
//       -12034 --> -12034
//       -2147483648 --> -2147483648
//       -2147483649: Overflow
Module Example
   Public Sub Main()
      Dim values() As String = { "+13230", "-0", "1,390,146", "$190,235,421,127",
                                 "0xFA1B", "163042", "-10", "007", "2147483647", 
                                 "2147483648", "16e07", "134985.0", "-12034",
                                 "-2147483648", "-2147483649"  }
      For Each value As String In values
         Try
            Dim number As Integer = Int32.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}: Overflow", value)   
         End Try  
      Next
   End Sub
End Module
' The example displays the following output:
'       +13230 --> 13230
'       -0 --> 0
'       1,390,146: Bad Format
'       $190,235,421,127: Bad Format
'       0xFA1B: Bad Format
'       163042 --> 163042
'       -10 --> -10
'       007 --> 7
'       2147483647 --> 2147483647
'       2147483648: Overflow
'       16e07: Bad Format
'       134985.0: Bad Format
'       -12034 --> -12034
'       -2147483648 --> -2147483648
'       -2147483649: Overflow

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, 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 Int32.Parse(String, NumberStyles) metodo o Int32.Parse(String, NumberStyles, IFormatProvider) .

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 Int32.Parse(String, NumberStyles, IFormatProvider) metodo .

Vedi anche

Si applica a

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analizza un intervallo di caratteri in un valore.

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

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 int Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<int>::Parse;
public static int Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> int
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As Integer

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 32 bit.

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

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 32 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 Int32.MinValue o maggiore di Int32.MaxValue.

-oppure-

s include cifre frazionarie diverse da zero.

Esempio

Nell'esempio seguente viene utilizzato il Int32.Parse(String, NumberStyles) metodo per analizzare le rappresentazioni di stringa di diversi Int32 valori. Le impostazioni cultura correnti per l'esempio sono en-US.

using namespace System;
using namespace System::Globalization;

public ref class ParseInt32
{
public:
   static void Main()
   {
      Convert("104.0", NumberStyles::AllowDecimalPoint);
      Convert("104.9", NumberStyles::AllowDecimalPoint);
      Convert(" $17,198,064.42", NumberStyles::AllowCurrencySymbol |
                                 NumberStyles::Number);
      Convert("103E06", NumberStyles::AllowExponent);
      Convert("-1,345,791", NumberStyles::AllowThousands);
      Convert("(1,345,791)", NumberStyles::AllowThousands |
                             NumberStyles::AllowParentheses);
   }

private:
   static void Convert(String^ value, NumberStyles style)
   {
      try
      {
         int number = Int32::Parse(value, style);
         Console::WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException^)
      {
         Console::WriteLine("Unable to convert '{0}'.", value);
      }
      catch (OverflowException^)
      {
         Console::WriteLine("'{0}' is out of range of the Int32 type.", value);
      }
   }
};

int main()
{
    ParseInt32::Main();
}
// The example displays the following output to the console:
//       Converted '104.0' to 104.
//       '104.9' is out of range of the Int32 type.
//       ' $17,198,064.42' is out of range of the Int32 type.
//       Converted '103E06' to 103000000.
//       Unable to convert '-1,345,791'.
//       Converted '(1,345,791)' to -1345791.
using System;
using System.Globalization;

public class ParseInt32
{
   public static void Main()
   {
      Convert("104.0", NumberStyles.AllowDecimalPoint);
      Convert("104.9", NumberStyles.AllowDecimalPoint);
      Convert(" $17,198,064.42", NumberStyles.AllowCurrencySymbol |
                                 NumberStyles.Number);
      Convert("103E06", NumberStyles.AllowExponent);
      Convert("-1,345,791", NumberStyles.AllowThousands);
      Convert("(1,345,791)", NumberStyles.AllowThousands |
                             NumberStyles.AllowParentheses);
   }

   private static void Convert(string value, NumberStyles style)
   {
      try
      {
         int number = Int32.Parse(value, style);
         Console.WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException)
      {
         Console.WriteLine("Unable to convert '{0}'.", value);
      }
      catch (OverflowException)
      {
         Console.WriteLine("'{0}' is out of range of the Int32 type.", value);
      }
   }
}
// The example displays the following output to the console:
//       Converted '104.0' to 104.
//       '104.9' is out of range of the Int32 type.
//       ' $17,198,064.42' is out of range of the Int32 type.
//       Converted '103E06' to 103000000.
//       Unable to convert '-1,345,791'.
//       Converted '(1,345,791)' to -1345791.
open System
open System.Globalization

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

convert "104.0" NumberStyles.AllowDecimalPoint
convert "104.9" NumberStyles.AllowDecimalPoint
convert " $17,198,064.42" (NumberStyles.AllowCurrencySymbol ||| NumberStyles.Number)
convert "103E06" NumberStyles.AllowExponent
convert "-1,345,791" NumberStyles.AllowThousands
convert "(1,345,791)" (NumberStyles.AllowThousands ||| NumberStyles.AllowParentheses)


// The example displays the following output to the console:
//       Converted '104.0' to 104.
//       '104.9' is out of range of the Int32 type.
//       ' $17,198,064.42' is out of range of the Int32 type.
//       Converted '103E06' to 103000000.
//       Unable to convert '-1,345,791'.
//       Converted '(1,345,791)' to -1345791.
Imports System.Globalization

Module ParseInt32
   Public Sub Main()
      Convert("104.0", NumberStyles.AllowDecimalPoint)    
      Convert("104.9", NumberStyles.AllowDecimalPoint)
      Convert(" $17,198,064.42", NumberStyles.AllowCurrencySymbol Or _
                                 NumberStyles.Number)
      Convert("103E06", NumberStyles.AllowExponent)  
      Convert("-1,345,791", NumberStyles.AllowThousands)
      Convert("(1,345,791)", NumberStyles.AllowThousands Or _
                             NumberStyles.AllowParentheses)
   End Sub
   
   Private Sub Convert(value As String, style As NumberStyles)
      Try
         Dim number As Integer = Int32.Parse(value, style)
         Console.WriteLine("Converted '{0}' to {1}.", value, number)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", value)
      Catch e As OverflowException
         Console.WriteLine("'{0}' is out of range of the Int32 type.", value)   
      End Try
   End Sub
End Module
' The example displays the following output to the console:
'       Converted '104.0' to 104.
'       '104.9' is out of range of the Int32 type.
'       ' $17,198,064.42' is out of range of the Int32 type.
'       Converted '103E06' to 103000000.
'       Unable to convert '-1,345,791'.
'       Converted '(1,345,791)' to -1345791.

Commenti

Il style parametro definisce gli elementi di stile ,ad esempio lo spazio vuoto, il simbolo di segno positivo o negativo o il simbolo separatore delle migliaia, 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]exponential_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. Gli spazi vuoti possono essere visualizzati all'inizio di s se include il NumberStyles.AllowLeadingWhite flag e possono essere visualizzati alla fine di s se style include il NumberStyles.AllowTrailingWhite flag .style
$ Simbolo di valuta specifico delle impostazioni cultura. La posizione nella stringa è definita dalle NumberFormatInfo.CurrencyNegativePattern proprietà e NumberFormatInfo.CurrencyPositivePattern 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

Cifre_frazionarie

exponential_digits
Sequenza di cifre da 0 a 9. Per fractional_digits, solo la cifra 0 è valida.
, Simbolo separatore delle migliaia specifico delle impostazioni cultura. Il separatore delle migliaia di impostazioni cultura correnti può essere visualizzato in s se style include il NumberStyles.AllowThousands flag .
. Simbolo di virgola decimale specifica delle impostazioni cultura. Il simbolo decimale delle impostazioni cultura corrente può essere visualizzato in s se style include il NumberStyles.AllowDecimalPoint flag . Solo la cifra 0 può essere visualizzata come cifra frazionaria per l'esito positivo dell'operazione di analisi; se fractional_digits include qualsiasi altra cifra, viene generata un'eccezione OverflowException .
e Carattere 'e' o 'E', che indica che il valore è rappresentato in notazione esponenziale. Il s parametro può rappresentare un numero in notazione esponenziale se style include il NumberStyles.AllowExponent flag .
hexdigits Sequenza di cifre esadecimali da 0 a f o da 0 a F.

Nota

Qualsiasi carattere NUL di terminazione (U+0000) in s viene ignorato dall'operazione di analisi, indipendentemente dal valore dell'argomento style .

Una stringa con solo cifre (che corrisponde allo NumberStyles.None stile) analizza sempre correttamente se si trova nell'intervallo del Int32 tipo. La maggior parte degli elementi di controllo membri rimanenti NumberStyles che possono essere ma non devono essere presenti nella stringa di input. La tabella seguente indica in che modo i singoli NumberStyles membri influiscono sugli elementi che possono essere presenti in s.

Valore NumberStyles Elementi consentiti in s oltre alle cifre
None Solo l'elemento digits .
AllowDecimalPoint Elementi separatore decimale ( . ) e cifre frazionarie .
AllowExponent Il s parametro può anche usare la notazione esponenziale.
AllowLeadingWhite Elemento ws all'inizio di s.
AllowTrailingWhite Elemento ws alla fine di s.
AllowLeadingSign Elemento di segno all'inizio di s.
AllowTrailingSign Elemento di segno alla fine di s.
AllowParentheses Elemento di segno sotto forma di parentesi che racchiude il valore numerico.
AllowThousands Elemento separatore delle migliaia ( , ).
AllowCurrencySymbol Elemento $.
Currency Tutti. Il s parametro non può rappresentare un numero esadecimale o un numero in notazione esponenziale.
Float L'elemento ws all'inizio o alla fine di s, segno all'inizio di se il simbolo decimale ( . ). Il s parametro può anche usare la notazione esponenziale.
Number Elementi wsseparatore sign, , migliaia ( , ) e separatore decimale ( . ).
Any Tutti gli stili, tranne s che non possono rappresentare un numero esadecimale.

Se viene usato il NumberStyles.AllowHexSpecifier flag, s deve essere un valore esadecimale senza un prefisso. Ad esempio, "C9AF3" analizza correttamente, ma "0xC9AF3" non. Gli unici flag che possono essere combinati con il s parametro sono NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. L'enumerazione NumberStyles include uno stile numerico composito, NumberStyles.HexNumber, che include entrambi i flag di spazio vuoto.

Il s parametro viene analizzato usando le informazioni di formattazione in un NumberFormatInfo oggetto inizializzato per le impostazioni cultura di sistema correnti. Per specificare le impostazioni cultura le cui informazioni di formattazione vengono utilizzate per l'operazione di analisi, chiamare l'overload Int32.Parse(String, NumberStyles, IFormatProvider) .

Vedi anche

Si applica a