Condividi tramite


Int32.TryParse Metodo

Definizione

Converte la rappresentazione di stringa di un numero nell'equivalente intero con segno a 32 bit. Un valore restituito indica se l'operazione è riuscita.

Overload

TryParse(String, IFormatProvider, Int32)

Tenta di analizzare una stringa in un valore.

TryParse(ReadOnlySpan<Char>, Int32)

Converte la rappresentazione dell'intervallo di un numero in uno stile e in un formato specifico delle impostazioni cultura specificati nell'equivalente intero con segno a 32 bit. Un valore restituito indica se la conversione è riuscita.

TryParse(String, Int32)

Converte la rappresentazione di stringa di un numero nell'equivalente intero con segno a 32 bit. Un valore restituito indica se la conversione è riuscita.

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)

Prova ad analizzare un intervallo di caratteri UTF-8 in un valore.

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32)

Tenta di analizzare un intervallo di caratteri in un valore.

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Int32)

Prova ad analizzare un intervallo di caratteri UTF-8 in un valore.

TryParse(ReadOnlySpan<Byte>, Int32)

Prova a convertire un intervallo di caratteri UTF-8 contenente la rappresentazione di stringa di un numero nell'equivalente intero con segno a 32 bit.

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int32)

Converte la rappresentazione dell'intervallo di un numero in uno stile e in un formato specifico delle impostazioni cultura specificati nell'equivalente intero con segno a 32 bit. Un valore restituito indica se la conversione è riuscita.

TryParse(String, NumberStyles, IFormatProvider, Int32)

Converte la rappresentazione di stringa di un numero in uno stile e un formato specifico delle impostazioni cultura specificati nell'equivalente intero con segno a 32 bit. Un valore restituito indica se la conversione è riuscita.

TryParse(String, IFormatProvider, Int32)

Origine:
Int32.cs
Origine:
Int32.cs
Origine:
Int32.cs

Tenta di analizzare una stringa in un valore.

public:
 static bool TryParse(System::String ^ s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = IParsable<int>::TryParse;
public static bool TryParse (string? s, IFormatProvider? provider, out int result);
static member TryParse : string * IFormatProvider * int -> bool
Public Shared Function TryParse (s As String, provider As IFormatProvider, ByRef result As Integer) As Boolean

Parametri

s
String

Stringa da analizzare.

provider
IFormatProvider

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

result
Int32

Quando termina, questo metodo contiene il risultato dell'analisi corretta s o di un valore non definito in caso di errore.

Restituisce

true se s è stato analizzato correttamente; in caso contrario, false.

Si applica a

TryParse(ReadOnlySpan<Char>, Int32)

Origine:
Int32.cs
Origine:
Int32.cs
Origine:
Int32.cs

Converte la rappresentazione dell'intervallo di un numero in uno stile e in un formato specifico delle impostazioni cultura specificati nell'equivalente intero con segno a 32 bit. Un valore restituito indica se la conversione è riuscita.

public:
 static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] int % result);
public static bool TryParse (ReadOnlySpan<char> s, out int result);
static member TryParse : ReadOnlySpan<char> * int -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As Integer) As Boolean

Parametri

s
ReadOnlySpan<Char>

Intervallo contenente i caratteri che rappresentano il numero da convertire.

result
Int32

Quando termina, questo metodo contiene il valore intero con segno a 32 bit equivalente al numero contenuto in s, se la conversione ha avuto esito positivo o zero se la conversione non è riuscita. La conversione non riesce se il parametro s è null o Empty, non è conforme a styleoppure rappresenta un numero minore di Int32.MinValue o maggiore di Int32.MaxValue. Questo parametro viene passato non inizializzato; qualsiasi valore originariamente fornito in result verrà sovrascritto.

Restituisce

true se s è stata convertita correttamente; in caso contrario, false.

Si applica a

TryParse(String, Int32)

Origine:
Int32.cs
Origine:
Int32.cs
Origine:
Int32.cs

Converte la rappresentazione di stringa di un numero nell'equivalente intero con segno a 32 bit. Un valore restituito indica se la conversione è riuscita.

public:
 static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] int % result);
public static bool TryParse (string s, out int result);
public static bool TryParse (string? s, out int result);
static member TryParse : string * int -> bool
Public Shared Function TryParse (s As String, ByRef result As Integer) As Boolean

Parametri

s
String

Stringa contenente un numero da convertire.

result
Int32

Quando termina, questo metodo contiene il valore intero con segno a 32 bit equivalente al numero contenuto in s, se la conversione ha avuto esito positivo o zero se la conversione non è riuscita. La conversione non riesce se il parametro s è null o Empty, non è del formato corretto oppure rappresenta un numero minore di Int32.MinValue o maggiore di Int32.MaxValue. Questo parametro viene passato non inizializzato; qualsiasi valore originariamente fornito in result verrà sovrascritto.

Restituisce

true se s è stata convertita correttamente; in caso contrario, false.

Esempio

Nell'esempio seguente viene chiamato il metodo Int32.TryParse(String, Int32) con diversi valori stringa.

using namespace System;


   void TryToParse(String^ value)
   {
      Int32 number;
      bool result = Int32::TryParse(value, number);
      if (result) {
         Console::WriteLine("Converted '{0}' to {1}.", value, number);
      }
      else {
         if (value == nullptr) value = "";
         Console::WriteLine("Attempted conversion of '{0}' failed.", value);
      }
   }


void main()
{
      TryToParse(nullptr);
      TryToParse("160519");
      TryToParse("9432.0");
      TryToParse("16,667");
      TryToParse("   -322   ");
      TryToParse("+4302");
      TryToParse("(100);");
      TryToParse("01FA");
}
// The example displays the following output:
//      Attempted conversion of '' failed.
//      Converted '160519' to 160519.
//      Attempted conversion of '9432.0' failed.
//      Attempted conversion of '16,667' failed.
//      Converted '   -322   ' to -322.
//      Converted '+4302' to 4302.
//      Attempted conversion of '(100);' failed.
//      Attempted conversion of '01FA' failed.
using System;

public class Example
{
   public static void Main()
   {
      string[] values = { null, "160519", "9432.0", "16,667",
                          "   -322   ", "+4302", "(100);", "01FA" };
      foreach (var value in values)
      {
         int number;

         bool success = int.TryParse(value, out number);
         if (success)
         {
            Console.WriteLine($"Converted '{value}' to {number}.");
         }
         else
         {
            Console.WriteLine($"Attempted conversion of '{value ?? "<null>"}' failed.");
         }
      }
   }
}
// The example displays the following output:
//       Attempted conversion of '<null>' failed.
//       Converted '160519' to 160519.
//       Attempted conversion of '9432.0' failed.
//       Attempted conversion of '16,667' failed.
//       Converted '   -322   ' to -322.
//       Converted '+4302' to 4302.
//       Attempted conversion of '(100);' failed.
//       Attempted conversion of '01FA' failed.
open System

let values = 
   [ null; "160519"; "9432.0"; "16,667"
     "   -322   "; "+4302"; "(100);"; "01FA" ]
for value in values do
    match Int32.TryParse value with
    | true, number -> 
        printfn $"Converted '{value}' to {number}."
    | _ -> 
        printfn $"""Attempted conversion of '{if isNull value then "<null>" else value}' failed."""
         
// The example displays the following output:
//       Attempted conversion of '<null>' failed.
//       Converted '160519' to 160519.
//       Attempted conversion of '9432.0' failed.
//       Attempted conversion of '16,667' failed.
//       Converted '   -322   ' to -322.
//       Converted '+4302' to 4302.
//       Attempted conversion of '(100);' failed.
//       Attempted conversion of '01FA' failed.
Module Example
   Public Sub Main()
      Dim values() As String = { Nothing, "160519", "9432.0", "16,667",
                                 "   -322   ", "+4302", "(100);", 
                                 "01FA" }

      For Each value In values
         Dim number As Integer
    
         Dim success As Boolean = Int32.TryParse(value, number)
         If success Then
            Console.WriteLine("Converted '{0}' to {1}.", value, number)
         Else
            Console.WriteLine("Attempted conversion of '{0}' failed.", 
                              If(value ,"<null>"))
         End If     
      Next
   End Sub
End Module
' The example displays the following output to the console:
'       Attempted conversion of '<null>' failed.
'       Converted '160519' to 160519.
'       Attempted conversion of '9432.0' failed.
'       Attempted conversion of '16,667' failed.
'       Converted '   -322   ' to -322.
'       Converted '+4302' to 4302.
'       Attempted conversion of '(100)' failed.
'       Attempted conversion of '01FA' failed.

Alcune delle stringhe che il metodo TryParse(String, Int32) non è in grado di convertire in questo esempio sono:

  • "9432.0". La conversione non riesce perché la stringa non può contenere un separatore decimale; deve contenere solo cifre integrali.

  • "16,667". La conversione non riesce perché la stringa non può contenere separatori di gruppo; deve contenere solo cifre integrali.

  • "(100)". La conversione non riesce perché la stringa non può contenere un segno negativo diverso da quello definito dalle proprietà NumberFormatInfo.NegativeSign e NumberFormatInfo.NumberNegativePattern delle impostazioni cultura correnti.

  • "01FA". La conversione non riesce perché la stringa non può contenere cifre esadecimali; deve contenere solo cifre decimali.

Commenti

Il metodo TryParse è simile al metodo Parse, ad eccezione del metodo TryParse non genera un'eccezione se la conversione non riesce. Elimina la necessità di usare la gestione delle eccezioni per testare un FormatException nel caso in cui s non sia valido e non possa essere analizzato correttamente.

Il parametro s contiene un numero di form:

[ws] [sign]digits[ws]

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

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

Il parametro s viene interpretato usando lo stile NumberStyles.Integer. Oltre alle cifre decimali, sono consentiti solo gli spazi iniziali e finali insieme a un segno iniziale. 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 metodo Int32.TryParse(String, NumberStyles, IFormatProvider, Int32).

Il parametro s viene analizzato usando le informazioni di formattazione in un oggetto NumberFormatInfo inizializzato per le impostazioni cultura di sistema correnti. Per altre informazioni, vedere CurrentInfo.

Questo overload del metodo TryParse interpreta tutte le cifre nel parametro s come cifre decimali. Per analizzare la rappresentazione di stringa di un numero esadecimale, chiamare l'overload Int32.TryParse(String, NumberStyles, IFormatProvider, Int32).

Vedi anche

Si applica a

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)

Origine:
Int32.cs
Origine:
Int32.cs

Prova ad analizzare un intervallo di caratteri UTF-8 in un valore.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = IUtf8SpanParsable<int>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, out int result);
static member TryParse : ReadOnlySpan<byte> * IFormatProvider * int -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider, ByRef result As Integer) As Boolean

Parametri

utf8Text
ReadOnlySpan<Byte>

Intervallo di caratteri UTF-8 da analizzare.

provider
IFormatProvider

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

result
Int32

In caso di restituzione, contiene il risultato dell'analisi corretta utf8Text o di un valore non definito in caso di errore.

Restituisce

true se utf8Text è stato analizzato correttamente; in caso contrario, false.

Si applica a

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32)

Origine:
Int32.cs
Origine:
Int32.cs
Origine:
Int32.cs

Tenta di analizzare un intervallo di caratteri in un valore.

public:
 static bool TryParse(ReadOnlySpan<char> s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = ISpanParsable<int>::TryParse;
public static bool TryParse (ReadOnlySpan<char> s, IFormatProvider? provider, out int result);
static member TryParse : ReadOnlySpan<char> * IFormatProvider * int -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), provider As IFormatProvider, ByRef result As Integer) As Boolean

Parametri

s
ReadOnlySpan<Char>

Intervallo di caratteri da analizzare.

provider
IFormatProvider

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

result
Int32

Quando termina, questo metodo contiene il risultato dell'analisi corretta so di un valore non definito in caso di errore.

Restituisce

true se s è stato analizzato correttamente; in caso contrario, false.

Si applica a

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Int32)

Origine:
Int32.cs
Origine:
Int32.cs

Prova ad analizzare un intervallo di caratteri UTF-8 in un valore.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);
static member TryParse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider * int -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean

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 su utf8Text.

result
Int32

In caso di restituzione, contiene il risultato dell'analisi corretta utf8Text o di un valore non definito in caso di errore.

Restituisce

true se utf8Text è stato analizzato correttamente; in caso contrario, false.

Si applica a

TryParse(ReadOnlySpan<Byte>, Int32)

Origine:
Int32.cs
Origine:
Int32.cs

Prova a convertire un intervallo di caratteri UTF-8 contenente la rappresentazione di stringa di un numero nell'equivalente intero con segno a 32 bit.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, [Runtime::InteropServices::Out] int % result);
public static bool TryParse (ReadOnlySpan<byte> utf8Text, out int result);
static member TryParse : ReadOnlySpan<byte> * int -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), ByRef result As Integer) As Boolean

Parametri

utf8Text
ReadOnlySpan<Byte>

Intervallo contenente i caratteri UTF-8 che rappresentano il numero da convertire.

result
Int32

Quando termina, questo metodo contiene il valore intero con segno a 32 bit equivalente al numero contenuto in utf8Text se la conversione ha avuto esito positivo oppure zero se la conversione non è riuscita. Questo parametro viene passato non inizializzato; qualsiasi valore specificato originariamente nel risultato verrà sovrascritto.

Restituisce

true se utf8Text è stata convertita correttamente; in caso contrario, false.

Si applica a

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int32)

Origine:
Int32.cs
Origine:
Int32.cs
Origine:
Int32.cs

Converte la rappresentazione dell'intervallo di un numero in uno stile e in un formato specifico delle impostazioni cultura specificati nell'equivalente intero con segno a 32 bit. Un valore restituito indica se la conversione è riuscita.

public:
 static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result);
public:
 static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider provider, out int result);
static member TryParse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider * int -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean

Parametri

s
ReadOnlySpan<Char>

Intervallo contenente i caratteri che rappresentano il numero da convertire. L'intervallo viene interpretato usando lo stile specificato da style.

style
NumberStyles

Combinazione bit per bit di 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 di formattazione specifiche delle impostazioni cultura su s.

result
Int32

Quando termina, questo metodo contiene il valore intero con segno a 32 bit equivalente al numero contenuto in s, se la conversione ha avuto esito positivo o zero se la conversione non è riuscita. La conversione non riesce se il parametro s è null o Empty, non è conforme a styleoppure rappresenta un numero minore di Int32.MinValue o maggiore di Int32.MaxValue. Questo parametro viene passato non inizializzato; qualsiasi valore originariamente fornito in result verrà sovrascritto.

Restituisce

true se s è stata convertita correttamente; in caso contrario, false.

Si applica a

TryParse(String, NumberStyles, IFormatProvider, Int32)

Origine:
Int32.cs
Origine:
Int32.cs
Origine:
Int32.cs

Converte la rappresentazione di stringa di un numero in uno stile e un formato specifico delle impostazioni cultura specificati nell'equivalente intero con segno a 32 bit. Un valore restituito indica se la conversione è riuscita.

public:
 static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result);
public:
 static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;
public static bool TryParse (string s, System.Globalization.NumberStyles style, IFormatProvider provider, out int result);
public static bool TryParse (string? s, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);
static member TryParse : string * System.Globalization.NumberStyles * IFormatProvider * int -> bool
Public Shared Function TryParse (s As String, style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean

Parametri

s
String

Stringa contenente un numero da convertire. La stringa viene interpretata usando lo stile specificato da style.

style
NumberStyles

Combinazione bit per bit di 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 di formattazione specifiche delle impostazioni cultura su s.

result
Int32

Quando termina, questo metodo contiene il valore intero con segno a 32 bit equivalente al numero contenuto in s, se la conversione ha avuto esito positivo o zero se la conversione non è riuscita. La conversione non riesce se il parametro s è null o Empty, non è conforme a styleoppure rappresenta un numero minore di Int32.MinValue o maggiore di Int32.MaxValue. Questo parametro viene passato non inizializzato; qualsiasi valore originariamente fornito in result verrà sovrascritto.

Restituisce

true se s è stata convertita correttamente; in caso contrario, false.

Eccezioni

style non è un valore di NumberStyles.

-o-

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

Esempio

Nell'esempio seguente viene chiamato il metodo Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) con diversi valori stringa e NumberStyles.

using namespace System;
using namespace System::Globalization;

void CallTryParse(String^ stringToConvert, NumberStyles styles)
{
      Int32 number;
      CultureInfo^ provider;

      // If currency symbol is allowed, use en-US culture. 
      if (((Int32) (styles & NumberStyles::AllowCurrencySymbol)) > 0)
         provider = gcnew CultureInfo("en-US");
      else
         provider = CultureInfo::InvariantCulture;

      bool result = Int32::TryParse(stringToConvert, styles, 
                                   provider, number);
      if (result)
         Console::WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
      else
         Console::WriteLine("Attempted conversion of '{0}' failed.", 
                           Convert::ToString(stringToConvert));
}

void main()
{
      String^ numericString;
      NumberStyles styles;

      numericString = "106779";
      styles = NumberStyles::Integer;
      CallTryParse(numericString, styles);

      numericString = "-30677";
      styles = NumberStyles::None;
      CallTryParse(numericString, styles);

      styles = NumberStyles::AllowLeadingSign;
      CallTryParse(numericString, styles);

      numericString = "301677-";
      CallTryParse(numericString, styles);

      styles = styles | NumberStyles::AllowTrailingSign;
      CallTryParse(numericString, styles);

      numericString = "$10634";
      styles = NumberStyles::Integer;
      CallTryParse(numericString, styles);

      styles = NumberStyles::Integer | NumberStyles::AllowCurrencySymbol;
      CallTryParse(numericString, styles);

      numericString = "10345.00";
      styles = NumberStyles::Integer | NumberStyles::AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "10345.72";
      styles = NumberStyles::Integer | NumberStyles::AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "22,593"; 
      styles = NumberStyles::Integer | NumberStyles::AllowThousands;
      CallTryParse(numericString, styles);

      numericString = "12E-01";
      styles = NumberStyles::Integer | NumberStyles::AllowExponent;
      CallTryParse(numericString, styles); 

      numericString = "12E03";
      CallTryParse(numericString, styles); 

      numericString = "80c1";
      CallTryParse(numericString, NumberStyles::HexNumber);

      numericString = "0x80C1";
      CallTryParse(numericString, NumberStyles::HexNumber);      
      Console::ReadLine();
}
// The example displays the following output:
//      Converted '106779' to 106779.
//      Attempted conversion of '-30677' failed.
//      Converted '-30677' to -30677.
//      Attempted conversion of '301677-' failed.
//      Converted '301677-' to -301677.
//      Attempted conversion of '$10634' failed.
//      Converted '$10634' to 10634.
//      Converted '10345.00' to 10345.
//      Attempted conversion of '10345.72' failed.
//      Converted '22,593' to 22593.
//      Attempted conversion of '12E-01' failed.
//      Converted '12E03' to 12000.
//      Converted '80c1' to 32961.
//      Attempted conversion of '0x80C1' failed.
using System;
using System.Globalization;

public class StringParsing
{
   public static void Main()
   {
      string numericString;
      NumberStyles styles;

      numericString = "106779";
      styles = NumberStyles.Integer;
      CallTryParse(numericString, styles);

      numericString = "-30677";
      styles = NumberStyles.None;
      CallTryParse(numericString, styles);

      styles = NumberStyles.AllowLeadingSign;
      CallTryParse(numericString, styles);

      numericString = "301677-";
      CallTryParse(numericString, styles);

      styles = styles | NumberStyles.AllowTrailingSign;
      CallTryParse(numericString, styles);

      numericString = "$10634";
      styles = NumberStyles.Integer;
      CallTryParse(numericString, styles);

      styles = NumberStyles.Integer | NumberStyles.AllowCurrencySymbol;
      CallTryParse(numericString, styles);

      numericString = "10345.00";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "10345.72";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "22,593";
      styles = NumberStyles.Integer | NumberStyles.AllowThousands;
      CallTryParse(numericString, styles);

      numericString = "12E-01";
      styles = NumberStyles.Integer | NumberStyles.AllowExponent;
      CallTryParse(numericString, styles);

      numericString = "12E03";
      CallTryParse(numericString, styles);

      numericString = "80c1";
      CallTryParse(numericString, NumberStyles.HexNumber);

      numericString = "0x80C1";
      CallTryParse(numericString, NumberStyles.HexNumber);
   }

   private static void CallTryParse(string stringToConvert, NumberStyles styles)
   {
      CultureInfo provider;

      // If currency symbol is allowed, use en-US culture.
      if ((styles & NumberStyles.AllowCurrencySymbol) > 0)
         provider = new CultureInfo("en-US");
      else
         provider = CultureInfo.InvariantCulture;

      bool success = int.TryParse(stringToConvert, styles,
                                   provider, out int number);
      if (success)
         Console.WriteLine($"Converted '{stringToConvert}' to {number}.");
      else
         Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed.");
   }
}
// The example displays the following output to the console:
//       Converted '106779' to 106779.
//       Attempted conversion of '-30677' failed.
//       Converted '-30677' to -30677.
//       Attempted conversion of '301677-' failed.
//       Converted '301677-' to -301677.
//       Attempted conversion of '$10634' failed.
//       Converted '$10634' to 10634.
//       Converted '10345.00' to 10345.
//       Attempted conversion of '10345.72' failed.
//       Converted '22,593' to 22593.
//       Attempted conversion of '12E-01' failed.
//       Converted '12E03' to 12000.
//       Converted '80c1' to 32961.
//       Attempted conversion of '0x80C1' failed.
open System
open System.Globalization

let callTryParse (stringToConvert: string) styles =
    let provider =
        // If currency symbol is allowed, use en-US culture.
        if int (styles &&& NumberStyles.AllowCurrencySymbol) > 0 then
            CultureInfo "en-US"
        else
            CultureInfo.InvariantCulture

    match Int32.TryParse(stringToConvert, styles, provider) with
    | true, number ->
        printfn $"Converted '{stringToConvert}' to {number}."
    | _ ->
        printfn $"Attempted conversion of '{stringToConvert}' failed."

[<EntryPoint>]
let main _ =
    let numericString = "106779"
    let styles = NumberStyles.Integer
    callTryParse numericString styles

    let numericString = "-30677"
    let styles = NumberStyles.None
    callTryParse numericString styles

    let styles = NumberStyles.AllowLeadingSign
    callTryParse numericString styles

    let numericString = "301677-"
    callTryParse numericString styles

    let styles = styles ||| NumberStyles.AllowTrailingSign
    callTryParse numericString styles

    let numericString = "$10634"
    let styles = NumberStyles.Integer
    callTryParse numericString styles

    let styles = NumberStyles.Integer ||| NumberStyles.AllowCurrencySymbol
    callTryParse numericString styles

    let numericString = "10345.00"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
    callTryParse numericString styles

    let numericString = "10345.72"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
    callTryParse numericString styles

    let numericString = "22,593"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowThousands
    callTryParse numericString styles

    let numericString = "12E-01"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowExponent
    callTryParse numericString styles

    let numericString = "12E03"
    callTryParse numericString styles

    let numericString = "80c1"
    callTryParse numericString NumberStyles.HexNumber

    let numericString = "0x80C1"
    callTryParse numericString NumberStyles.HexNumber

    0

// The example displays the following output to the console:
//       Converted '106779' to 106779.
//       Attempted conversion of '-30677' failed.
//       Converted '-30677' to -30677.
//       Attempted conversion of '301677-' failed.
//       Converted '301677-' to -301677.
//       Attempted conversion of '$10634' failed.
//       Converted '$10634' to 10634.
//       Converted '10345.00' to 10345.
//       Attempted conversion of '10345.72' failed.
//       Converted '22,593' to 22593.
//       Attempted conversion of '12E-01' failed.
//       Converted '12E03' to 12000.
//       Converted '80c1' to 32961.
//       Attempted conversion of '0x80C1' failed.
Imports System.Globalization

Module StringParsing
   Public Sub Main()
      Dim numericString As String
      Dim styles As NumberStyles
      
      numericString = "106779"
      styles = NumberStyles.Integer
      CallTryParse(numericString, styles)
      
      numericString = "-30677"
      styles = NumberStyles.None
      CallTryParse(numericString, styles)
      
      styles = NumberStyles.AllowLeadingSign
      CallTryParse(numericString, styles)
      
      numericString = "301677-"
      CallTryParse(numericString, styles)
      
      styles = styles Or NumberStyles.AllowTrailingSign
      CallTryParse(numericString, styles)
      
      numericString = "$10634"
      styles = NumberStyles.Integer
      CallTryParse(numericString, styles)
      
      styles = NumberStyles.Integer Or NumberStyles.AllowCurrencySymbol
      CallTryParse(numericString, styles)

      numericString = "10345.00"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)
      
      numericString = "10345.72"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)

      numericString = "22,593" 
      styles = NumberStyles.Integer Or NumberStyles.AllowThousands
      CallTryParse(numericString, styles)
      
      numericString = "12E-01"
      styles = NumberStyles.Integer Or NumberStyles.AllowExponent
      CallTryParse(numericString, styles) 
          
      numericString = "12E03"
      CallTryParse(numericString, styles) 
      
      numericString = "80c1"
      CallTryParse(numericString, NumberStyles.HexNumber)
      
      numericString = "0x80C1"
      CallTryParse(numericString, NumberStyles.HexNumber)
   End Sub
   
   Private Sub CallTryParse(stringToConvert As String, styles AS NumberStyles)
      Dim number As Integer
      Dim provider As CultureInfo
      
      ' If currency symbol is allowed, use en-US culture.
      If CBool(styles And NumberStyles.AllowCurrencySymbol) Then
         provider = CultureInfo.CurrentCulture
      Else
         provider = New CultureInfo("en-US")
      End If
      
      Dim result As Boolean = Int32.TryParse(stringToConvert, styles, _
                                             provider, number)
      If result Then
         Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
      Else
         Console.WriteLine("Attempted conversion of '{0}' failed.", _
                           Convert.ToString(stringToConvert))
      End If                                                                           
   End Sub
End Module
' The example displays the following output to the console:
'       Converted '106779' to 106779.
'       Attempted conversion of '-30677' failed.
'       Converted '-30677' to -30677.
'       Attempted conversion of '301677-' failed.
'       Converted '301677-' to -301677.
'       Attempted conversion of '$10634' failed.
'       Converted '$10634' to 10634.
'       Converted '10345.00' to 10345.
'       Attempted conversion of '10345.72' failed.
'       Converted '22,593' to 22593.
'       Attempted conversion of '12E-01' failed.
'       Converted '12E03' to 12000.
'       Converted '80c1' to 32961.
'       Attempted conversion of '0x80C1' failed.

Commenti

Il metodo TryParse è simile al metodo Parse, ad eccezione del metodo TryParse non genera un'eccezione se la conversione non riesce. Elimina la necessità di usare la gestione delle eccezioni per testare un FormatException nel caso in cui s non sia valido e non possa essere analizzato correttamente.

Il parametro style definisce gli elementi di stile(ad esempio uno spazio vuoto o un segno positivo o negativo) consentiti nel parametro s 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 parametro s può includere gli elementi seguenti:

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

In alternativa, se il parametro style include AllowHexSpecifier:

[ws]hexdigits[ws]

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

Elemento Descrizione
ws Spazio vuoto facoltativo. Gli spazi vuoti possono essere visualizzati all'inizio di s se style include il flag di NumberStyles.AllowLeadingWhite o alla fine del s se style include il flag di NumberStyles.AllowTrailingWhite.
$ Simbolo di valuta specifico delle impostazioni cultura. La posizione nella stringa è definita dalla proprietà CurrencyPositivePattern dell'oggetto NumberFormatInfo restituito dal metodo GetFormat del parametro provider. Il simbolo di valuta può essere visualizzato in s se style include il flag di NumberStyles.AllowCurrencySymbol.
firmare Segno facoltativo. Un simbolo di segno può essere visualizzato in s se style include i flag NumberStyles.AllowLeadingSign o NumberStyles.AllowTrailingSign.
cifre Sequenza di cifre da 0 a 9.
, Separatore delle migliaia specifico delle impostazioni cultura. Il separatore delle migliaia delle impostazioni cultura specificate da provider può essere visualizzato in s se style include il flag NumberStyles.AllowThousands.
. Simbolo di virgola decimale specifica delle impostazioni cultura. Il simbolo di virgola decimale delle impostazioni cultura specificate da provider può essere visualizzato in s se style include il flag NumberStyles.AllowDecimalPoint.
fractional_digits Una o più occorrenze della cifra 0. Le cifre frazionarie possono essere visualizzate in s solo se style include il flag di NumberStyles.AllowDecimalPoint.
e Carattere 'e' o 'E', che indica che il valore è rappresentato nella notazione esponenziale. Il parametro s può rappresentare un numero in notazione esponenziale se style include il flag NumberStyles.AllowExponent.
hexdigits Sequenza di cifre esadecimali da 0 a f o da 0 a F.

Nota

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

Una stringa con solo cifre decimali (che corrisponde al flag di NumberStyles.None) viene sempre analizzata correttamente. La maggior parte dei membri rimanenti NumberStyles elementi di controllo che possono essere ma non devono essere presenti in questa stringa di input. La tabella seguente indica in che modo i singoli membri NumberStyles 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 Il separatore decimale (.) e gli elementi fractional_digits. Tuttavia, fractional_digits deve essere costituito da una o più cifre 0 oppure il metodo restituisce false.
NumberStyles.AllowExponent Il parametro s può anche usare la notazione esponenziale. Se s rappresenta un numero in notazione esponenziale, deve rappresentare un numero intero compreso nell'intervallo del tipo di dati Int32 senza un componente frazionaria diverso da zero.
NumberStyles.AllowLeadingWhite Elemento ws all'inizio di .
NumberStyles.AllowTrailingWhite Elemento ws alla fine di .
NumberStyles.AllowLeadingSign Un segno può essere visualizzato prima di cifre.
NumberStyles.AllowTrailingSign Un segno può essere visualizzato dopo cifre.
NumberStyles.AllowParentheses Elemento segno sotto forma di parentesi che racchiudono il valore numerico.
NumberStyles.AllowThousands Elemento separatore delle migliaia (,).
NumberStyles.AllowCurrencySymbol Elemento $.
NumberStyles.Currency Tutti gli elementi. Il parametro s non può rappresentare un numero esadecimale o un numero in notazione esponenziale.
NumberStyles.Float L'elemento ws all'inizio o alla fine di , segno all'inizio di e il simbolo decimale (.). Il parametro s può anche usare la notazione esponenziale.
NumberStyles.Number Elementi ws, segno, separatore delle migliaia (,) e separatore decimale (.).
NumberStyles.Any Tutti gli stili, ad eccezione di s non possono rappresentare un numero esadecimale.

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

Il parametro provider è un'implementazione IFormatProvider, ad esempio un oggetto CultureInfo o un oggetto NumberFormatInfo, il cui metodo GetFormat restituisce un oggetto NumberFormatInfo. L'oggetto NumberFormatInfo 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