Share via


Procedura: convertire una stringa in un Integer (Guida per programmatori C#)

In questi esempi vengono illustrate alcune modalità diverse che è possibile utilizzare per convertire un valore string in un valore int. Tale conversione può essere utile quando si ottiene input numerico da un argomento della riga di comando, ad esempio. Sono disponibili metodi simili per la conversione di stringhe in altri tipi numerici, ad esempio float o long. Nella tabella riportata di seguito sono elencati alcuni di questi metodi.

Tipo numerico

Metodo

decimal

ToDecimal(String)

float

ToSingle(String)

double

ToDouble(String)

short

ToInt16(String)

long

ToInt64(String)

ushort

ToUInt16(String)

uint

ToUInt32(String)

ulong

ToUInt64(String)

Esempio

In questo esempio viene chiamato il metodo ToInt32(String) per convertire un tipo string di input in un tipo int. Il programma rileva le due eccezioni più comuni che possono essere generate da questo metodo. Se è possibile incrementare il numero senza provocare l'overflow nella posizione di archiviazione di Integer, il programma aggiunge 1 al risultato e stampa l'output.

int numVal = -1;
bool repeat = true;

while (repeat == true)
{
    Console.WriteLine("Enter a number between −2,147,483,648 and +2,147,483,647 (inclusive).");

    string input = Console.ReadLine();

    // ToInt32 can throw FormatException or OverflowException.
    try
    {
        numVal = Convert.ToInt32(input);
    }
    catch (FormatException e)
    {
        Console.WriteLine("Input string is not a sequence of digits.");
    }
    catch (OverflowException e)
    {
        Console.WriteLine("The number cannot fit in an Int32.");
    }
    finally
    {
        if (numVal < Int32.MaxValue)
        {
            Console.WriteLine("The new value is {0}", numVal + 1);
        }
        else
        {
            Console.WriteLine("numVal cannot be incremented beyond its current value");
        }
    }
    Console.WriteLine("Go again? Y/N");
    string go = Console.ReadLine();
    if (go == "Y" || go == "y")
    {
        repeat = true;
    }
    else
    {
        repeat = false;
    }
}
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();    

Un altro modo per convertire un valore string in un valore int consiste nell'utilizzare il metodo Parse o TryParse della struttura System.Int32. Il metodo ToUInt32 utilizza il metodo Parse internamente. Se il formato della stringa non è valido, il metodo Parse genera un'eccezione, mentre il metodo TryParse non genera un'eccezione ma restituisce false. Negli esempi riportati di seguito vengono illustrate chiamate con esito positivo e negativo ai metodi Parse e TryParse.

int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105
// TryParse returns true if the conversion succeeded
// and stores the result in the specified variable.
int j;
bool result = Int32.TryParse("-105", out j);
if (true == result)
    Console.WriteLine(j);
else
    Console.WriteLine("String could not be parsed.");
// Output: -105
try
{
    int m = Int32.Parse("abc");
}
catch (FormatException e)
{
    Console.WriteLine(e.Message);
}
// Output: Input string was not in a correct format.
string inputString = "abc";
int numValue;
bool parsed = Int32.TryParse(inputString, out numValue);

if (!parsed)
    Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString);

// Output: Int32.TryParse could not parse 'abc' to an int.

Vedere anche

Attività

Procedura: determinare se una stringa rappresenta un valore numerico (Guida per programmatori C#)

Riferimenti

Tipi (Guida per programmatori C#)