Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Chuyển chuỗi sang int trong C#

Chuỗi: string str = "9999";

Dùng Int32.Parse hoặc int.Parse:

int n = Int32.Parse(str);

Ví dụ

using System;

class Demo
{
    static void Main()
    {
        string str = "9999";
        int n = Int32.Parse(str);
        Console.WriteLine(n);
    }
}

Các cách chuyển đổi

MethodException nếu failGhi chú
int.ParseFormatException, OverflowExceptionNhanh, cho input tin cậy
int.TryParseKhông (trả bool)An toàn, khuyến nghị
Convert.ToInt32FormatException, OverflowExceptionXử lý null -> 0

TryParse pattern (khuyến nghị)

if (int.TryParse(str, out int n))
    Console.WriteLine($"Parsed: {n}");
else
    Console.WriteLine("Không phải số nguyên hợp lệ");

NumberStyles: int.Parse("1,234", NumberStyles.AllowThousands) cho phép dấu phẩy.