Int32.TryParse Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
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(ReadOnlySpan<Byte>, IFormatProvider, Int32) |
Tenta di analizzare un intervallo di caratteri UTF-8 in un valore. |
TryParse(ReadOnlySpan<Char>, Int32) |
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. 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<Char>, IFormatProvider, Int32) |
Tenta di analizzare un intervallo di caratteri in un valore. |
TryParse(String, IFormatProvider, Int32) |
Tenta di analizzare una stringa in un valore. |
TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Int32) |
Tenta di analizzare un intervallo di caratteri UTF-8 in un valore. |
TryParse(ReadOnlySpan<Byte>, Int32) |
Tenta di 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 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. Un valore restituito indica se la conversione è riuscita. |
TryParse(String, NumberStyles, IFormatProvider, Int32) |
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. Un valore restituito indica se la conversione è riuscita. |
TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)
- Origine:
- Int32.cs
- Origine:
- Int32.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] 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 relative a utf8Text
.
- result
- Int32
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>, Int32)
- Origine:
- Int32.cs
- Origine:
- Int32.cs
- Origine:
- Int32.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 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 questo metodo viene restituito, contiene l'intero con segno a 32 bit equivalente al numero contenuto in s
, se la conversione riesce oppure zero se la conversione non riesce. La conversione non riesce se il s
parametro è null
o Empty, non è conforme a style
o rappresenta un numero minore di Int32.MinValue o maggiore di Int32.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, 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 che contiene un numero da convertire.
- result
- Int32
Quando questo metodo viene restituito, contiene l'intero con segno a 32 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 Int32.MinValue o maggiore di Int32.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 Int32.TryParse(String, Int32) metodo con un numero di valori stringa diversi.
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 TryParse(String, Int32) 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 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) 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 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) .
Vedi anche
- Parse(String)
- ToString()
- Analisi di stringhe numeriche in .NET
- Esempio: Utilità di formattazione di .NET Core WinForms (C#)
- Esempio: Utilità di formattazione di .NET Core WinForms (Visual Basic)
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 relative a s
.
- result
- Int32
Quando termina, questo metodo contiene il risultato dell'analisi s
corretta 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, 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 relative a s
.
- result
- Int32
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, Int32)
- Origine:
- Int32.cs
- Origine:
- Int32.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] 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 relative a utf8Text
.
- result
- Int32
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>, Int32)
- Origine:
- Int32.cs
- Origine:
- Int32.cs
Tenta di 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 o zero se la conversione non riesce. 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, Int32)
- Origine:
- Int32.cs
- Origine:
- Int32.cs
- Origine:
- Int32.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 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. 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
- Int32
Quando questo metodo viene restituito, contiene l'intero con segno a 32 bit equivalente al numero contenuto in s
, se la conversione riesce oppure zero se la conversione non riesce. La conversione non riesce se il s
parametro è null
o Empty, non è conforme a style
o rappresenta un numero minore di Int32.MinValue o maggiore di Int32.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, Int32)
- Origine:
- Int32.cs
- Origine:
- Int32.cs
- Origine:
- Int32.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 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 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
- Int32
Quando questo metodo viene restituito, contiene l'intero con segno a 32 bit equivalente al numero contenuto in s
, se la conversione riesce oppure zero se la conversione non riesce. La conversione non riesce se il s
parametro è null
o Empty, non è conforme a style
o rappresenta un numero minore di Int32.MinValue o maggiore di Int32.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 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) metodo con una serie di valori e NumberStyles stringhe diversi.
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 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 style
parametro definisce gli elementi di stile( ad esempio uno spazio vuoto o un segno positivo o negativo) consentiti nel s
parametro per l'esito positivo dell'operazione di analisi. Deve essere una combinazione di flag di bit dell'enumerazione NumberStyles . A seconda del valore di style
, il s
parametro può includere gli elementi seguenti:
[ws] [$] [sign] [digits,]digits[.fractional_digits][e[sign]digits][ws]
In alternativa, se il style
parametro include AllowHexSpecifier:
[ws]hexdigits[ws]
Gli elementi tra parentesi quadre ([ e ]) sono facoltativi. La tabella seguente descrive i singoli elementi.
Elemento | Descrizione |
---|---|
ws | Spazio vuoto facoltativo. Lo spazio vuoto può essere visualizzato all'inizio di s se include il NumberStyles.AllowLeadingWhite flag o alla fine di s se style include il NumberStyles.AllowTrailingWhite flag .style |
$ | Simbolo di valuta specifico delle impostazioni cultura. La posizione nella stringa è definita dalla 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 | Sequenza di cifre da 0 a 9. |
, | Separatore delle migliaia specifiche delle impostazioni cultura. Il separatore delle migliaia delle impostazioni cultura specificate da provider può essere visualizzato in s se style include il NumberStyles.AllowThousands flag . |
. | 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 NumberStyles.AllowDecimalPoint flag . |
Cifre_frazionarie | Una o più occorrenze della cifra 0. Le cifre frazionarie possono essere visualizzate solo s se style include il NumberStyles.AllowDecimalPoint flag . |
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 decimali (che corrisponde al NumberStyles.None flag) analizza sempre correttamente. La maggior parte degli elementi di controllo membri rimanenti NumberStyles che possono essere ma non devono essere presenti in questa stringa di input. La tabella seguente indica in che modo 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 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 s parametro può anche usare la notazione esponenziale. Se s rappresenta un numero in notazione esponenziale, deve rappresentare un numero intero all'interno dell'intervallo del Int32 tipo di 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 delle 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 s e simbolo decimale (.). Il s parametro può anche usare la notazione esponenziale. |
NumberStyles.Number | Elementi ws, segno, separatore delle migliaia (,) e separatore decimale (.). |
NumberStyles.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 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 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 utilizzato l'oggetto NumberFormatInfo per le impostazioni cultura correnti.
Vedi anche
Si applica a
Commenti e suggerimenti
https://aka.ms/ContentUserFeedback.
Presto disponibile: Nel corso del 2024 verranno gradualmente disattivati i problemi di GitHub come meccanismo di feedback per il contenuto e ciò verrà sostituito con un nuovo sistema di feedback. Per altre informazioni, vedereInvia e visualizza il feedback per