Aracılığıyla paylaş


Nasıl yapılır: Bir dizeyi sayıya dönüştürme (C# Programlama Kılavuzu)

Bu örnekler, dönüştürebilirsiniz bazı farklı şekillerde bir dize için bir int.Bir dönüştürme, komut satırı bağımsız değişkeninden, örneğin sayısal giriş elde ederken yararlı olabilir.Benzer yöntemler mevcut dizelerin sayısal diğer türleri gibi dönüştürmek için float veya uzun.Aşağıdaki tabloda bu yöntemlerden bazıları listelenmiştir.

Sayısal tür

Method

decimal

ToDecimal(String)

float

ToSingle(String)

double

ToDouble(String)

short

ToInt16(String)

int

ToInt32(String)

long

ToInt64(String)

ushort

ToUInt16(String)

uint

ToUInt32(String)

ulong

ToUInt64(String)

Örnek

Bu örnek çağırır ToInt32(String) giriş dönüştürmek için yöntem dize için bir int .Program bu yöntem tarafından atılan iki yaygın özel durumları yakalar FormatException ve OverflowException.Sayı tamsayı depolama konumu taşmadan 'er artırılabilir, program sonuca 1 ekler ve çıktısı yazdırır.

static void Main(string[] args)
{
    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();    
}
// Sample Output:
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// 473
// The new value is 474
// Go again? Y/N
// y
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// 2147483647
// numVal cannot be incremented beyond its current value
// Go again? Y/N
// Y
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// -1000
// The new value is -999
// Go again? Y/N
// n
// Press any key to exit.

Dönüştürme başka bir yolu bir string için bir int üzerinden Parse veya TryParse yöntemleri System.Int32 yapı.ToUInt32 Yöntemi kullanan Parse dahili olarak.Dize geçerli bir biçimde değil, Parse , ancak bir istisna atar TryParse bir özel durum oluşturmaz ancak verir yanlış.Aşağıdaki örnekler göstermek için başarılı ve başarısız çağrıların Parse ve 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.

Ayrıca bkz.

Görevler

Nasıl yapılır: bir dize sayısal bir değer (C# Programlama Kılavuzu) temsil edip etmediğini belirlemek

Başvuru

Türleri (C# Programlama Kılavuzu)