Int64.TryParse Metodo

Definizione

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

Overload

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int64)

Tenta di analizzare un intervallo di caratteri UTF-8 in un valore.

TryParse(ReadOnlySpan<Char>, Int64)

Converte la rappresentazione in forma di intervallo di un numero nell'intero con segno a 64 bit equivalente. Un valore restituito indica se la conversione è riuscita o meno.

TryParse(String, Int64)

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

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int64)

Tenta di analizzare un intervallo di caratteri in un valore.

TryParse(String, IFormatProvider, Int64)

Tenta di analizzare una stringa in un valore.

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

Tenta di analizzare un intervallo di caratteri UTF-8 in un valore.

TryParse(ReadOnlySpan<Byte>, Int64)

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

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

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 64 bit. Un valore restituito indica se la conversione è riuscita o meno.

TryParse(String, NumberStyles, IFormatProvider, Int64)

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 64 bit. Un valore restituito indica se la conversione è riuscita o meno.

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int64)

Source:
Int64.cs
Source:
Int64.cs

Tenta di analizzare un intervallo di caratteri UTF-8 in un valore.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider, [Runtime::InteropServices::Out] long % result) = IUtf8SpanParsable<long>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, out long result);
static member TryParse : ReadOnlySpan<byte> * IFormatProvider * int64 -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider, ByRef result As Long) 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 relative a utf8Text.

result
Int64

In caso di restituzione, contiene il risultato dell'analisi utf8Text corretta 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>, Int64)

Source:
Int64.cs
Source:
Int64.cs
Source:
Int64.cs

Converte la rappresentazione in forma di intervallo di un numero nell'intero con segno a 64 bit equivalente. Un valore restituito indica se la conversione è riuscita o meno.

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

Parametri

s
ReadOnlySpan<Char>

Intervallo contenente i caratteri che rappresentano il numero da convertire.

result
Int64

Quando questo metodo viene restituito, contiene l'intero con segno a 64 bit equivalente al numero contenuto in s, se la conversione riesce oppure zero se la conversione non riesce. La conversione ha esito negativo se il s parametro è null o Empty, non è del formato corretto oppure rappresenta un numero minore di Int64.MinValue o maggiore di Int64.MaxValue. Questo parametro viene passato non inizializzato. Qualsiasi valore fornito in origine in result verrà sovrascritto.

Restituisce

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

Si applica a

TryParse(String, Int64)

Source:
Int64.cs
Source:
Int64.cs
Source:
Int64.cs

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

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

Parametri

s
String

Stringa che contiene un numero da convertire.

result
Int64

Quando questo metodo viene restituito, contiene l'intero con segno a 64 bit equivalente al numero contenuto in s, se la conversione riesce oppure zero se la conversione non riesce. La conversione ha esito negativo se il s parametro è null o Empty, non è del formato corretto oppure rappresenta un numero minore di Int64.MinValue o maggiore di Int64.MaxValue. Questo parametro viene passato non inizializzato. Qualsiasi valore fornito in origine in result verrà sovrascritto.

Restituisce

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

Esempio

Nell'esempio seguente viene chiamato il Int64.TryParse(String, Int64) metodo con un numero di valori stringa diversi.

using System;

public class StringParsing
{
   public static void Main()
   {
      TryToParse(null);
      TryToParse("160519");
      TryToParse("9432.0");
      TryToParse("16,667");
      TryToParse("   -322   ");
      TryToParse("+4302");
      TryToParse("(100);");
      TryToParse("01FA");
   }

   private static void TryToParse(string value)
   {
      bool success = Int64.TryParse(value, out long number);
      if (success)
      {
         Console.WriteLine("Converted '{0}' to {1}.", value, number);
      }
      else
      {
         if (value == null) value = "";
         Console.WriteLine("Attempted conversion of '{0}' failed.", value);
      }
   }
}
// The example displays the following output to the console:
//       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.
open System

let tryToParse (value: string) =
    match Int64.TryParse value with
    | true, number ->
        printfn $"Converted '{value}' to {number}."
    | _ ->
        let value =
            if isNull value then 
                ""
            else
                value
        printfn $"Attempted conversion of '{value}' failed."

tryToParse null
tryToParse "160519"
tryToParse "9432.0"
tryToParse "16,667"
tryToParse "   -322   "
tryToParse "+4302"
tryToParse "(100);"
tryToParse "01FA"


// The example displays the following output to the console:
//       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.
Module StringParsing
   Public Sub Main()
      TryToParse(Nothing)
      TryToParse("160519")
      TryToParse("9432.0")
      TryToParse("16,667")
      TryToParse("   -322   ")
      TryToParse("+4302")
      TryToParse("(100)")
      TryToParse("01FA")
   End Sub
   
   Private Sub TryToParse(value As String)
      Dim number As Long
      Dim result As Boolean = Int64.TryParse(value, number)
      If result Then
         Console.WriteLine("Converted '{0}' to {1}.", value, number)
      Else
         If value Is Nothing Then value = "" 
         Console.WriteLine("Attempted conversion of '{0}' failed.", value)
      End If     
   End Sub
End Module
' The example displays the following output to the console:
'       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.

Alcune delle stringhe che il TryParse(String, Int64) metodo 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à e NumberFormatInfo.NumberNegativePattern delle impostazioni cultura NumberFormatInfo.NegativeSign correnti.

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

Commenti

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

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 insieme alle informazioni di formattazione specifiche delle impostazioni cultura che possono essere presenti in s, usare il TryParse(String, NumberStyles, IFormatProvider, Int64) metodo .

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.

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

Vedi anche

Si applica a

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int64)

Source:
Int64.cs
Source:
Int64.cs
Source:
Int64.cs

Tenta di analizzare un intervallo di caratteri in un valore.

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

Parametri

s
ReadOnlySpan<Char>

Intervallo di caratteri da analizzare.

provider
IFormatProvider

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

result
Int64

Quando termina, questo metodo contiene il risultato dell'analisi scorretta di 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(String, IFormatProvider, Int64)

Source:
Int64.cs
Source:
Int64.cs
Source:
Int64.cs

Tenta di analizzare una stringa in un valore.

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

Parametri

s
String

Stringa da analizzare.

provider
IFormatProvider

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

result
Int64

Quando termina, questo metodo contiene il risultato dell'analisi s corretta 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<Byte>, NumberStyles, IFormatProvider, Int64)

Source:
Int64.cs
Source:
Int64.cs

Tenta di 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] long % result) = System::Numerics::INumberBase<long>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style, IFormatProvider? provider, out long result);
static member TryParse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider * int64 -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), style As NumberStyles, provider As IFormatProvider, ByRef result As Long) 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 relative a utf8Text.

result
Int64

In caso di restituzione, contiene il risultato dell'analisi utf8Text corretta 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>, Int64)

Source:
Int64.cs
Source:
Int64.cs

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

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

Parametri

utf8Text
ReadOnlySpan<Byte>

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

result
Int64

Quando questo metodo restituisce, contiene il valore intero con segno a 64 bit equivalente al numero contenuto in utf8Text se la conversione ha avuto esito positivo o zero se la conversione non è riuscita. Questo parametro viene passato non inizializzato. Qualsiasi valore specificato in origine in result verrà sovrascritto.

Restituisce

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

Si applica a

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

Source:
Int64.cs
Source:
Int64.cs
Source:
Int64.cs

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 64 bit. Un valore restituito indica se la conversione è riuscita o meno.

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

Parametri

s
ReadOnlySpan<Char>

Intervallo contenente i caratteri che rappresentano il numero da convertire. Per interpretare l'intervallo, viene usato lo stile specificato da style.

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 di formattazione specifiche delle impostazioni cultura relativamente a s.

result
Int64

Quando questo metodo viene restituito, contiene l'intero con segno a 64 bit equivalente al numero contenuto in s, se la conversione riesce oppure zero se la conversione non riesce. La conversione ha esito negativo se il s parametro è o Empty, non è null conforme a styleo rappresenta un numero minore di Int64.MinValue o maggiore di Int64.MaxValue. Questo parametro viene passato non inizializzato. Qualsiasi valore fornito in origine in result verrà sovrascritto.

Restituisce

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

Si applica a

TryParse(String, NumberStyles, IFormatProvider, Int64)

Source:
Int64.cs
Source:
Int64.cs
Source:
Int64.cs

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 64 bit. Un valore restituito indica se la conversione è riuscita o meno.

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

Parametri

s
String

Stringa che contiene un numero da convertire. La stringa viene interpreta usando lo stile specificato da style.

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 di formattazione specifiche delle impostazioni cultura relativamente a s.

result
Int64

Quando questo metodo viene restituito, contiene l'intero con segno a 64 bit equivalente al numero contenuto in s, se la conversione riesce oppure zero se la conversione non riesce. La conversione ha esito negativo se il s parametro è o Empty, non è null conforme a styleo rappresenta un numero minore di Int64.MinValue o maggiore di Int64.MaxValue. Questo parametro viene passato non inizializzato. Qualsiasi valore fornito in origine in result verrà sovrascritto.

Restituisce

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

Eccezioni

style non è un valore di NumberStyles.

-oppure-

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

Esempio

Nell'esempio seguente viene chiamato il TryParse(String, NumberStyles, IFormatProvider, Int64) metodo con un numero di stringhe e NumberStyles valori diversi.

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 = Int64.TryParse(stringToConvert, styles,
                                   provider, out long 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 Int64.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 Long
      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 = Int64.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 TryParse metodo è simile al Parse metodo, ad eccezione del TryParse metodo non genera un'eccezione se la conversione ha esito negativo. Elimina la necessità di usare la gestione delle eccezioni per testare un FormatException oggetto nell'evento non s valido e non può essere analizzato correttamente.

Il style parametro definisce gli elementi di stile , ad esempio spazio vuoto o segno positivo o negativo, consentiti nel s parametro per l'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]exponential_digits][ws]

In alternativa, se il style parametro include NumberStyles.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 sua posizione nella stringa è definita dalla 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. Un simbolo di segno può essere visualizzato in s se include i NumberStyles.AllowLeadingSign flag o NumberStyles.AllowTrailingSignstyle.
Cifre

Cifre_frazionarie

exponential_digits
Sequenza di cifre da 0 a 9. Per fractional_digits, solo la cifra 0 è valida.
, Separatore di migliaia specifiche 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.
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 al NumberStyles.None flag) 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 Il punto decimale ( . ) e gli elementi fractional_digits . Tuttavia, fractional_digits deve essere costituito da una o più cifre o il metodo restituisce false.
NumberStyles.AllowExponent Il s parametro può anche usare la notazione esponenziale. Il s parametro deve rappresentare un intero all'interno dell'intervallo del tipo di Int64 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 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 separatore migliaia ( , ).
NumberStyles.AllowCurrencySymbol Elemento $.
NumberStyles.Currency Tutti gli elementi. Il s parametro non può rappresentare un numero esadecimale o un numero in notazione esponenziale.
NumberStyles.Float 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.
NumberStyles.Number Elementi ws, sign, migliaia di separatori (,) e decimale (.).
NumberStyles.Any Tutti gli stili, tranne s non possono rappresentare un numero esadecimale.

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 composito, , NumberStyles.HexNumberche include entrambi i flag di spazi vuoti.

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