แปลงการแสดงสตริงของตัวเลขเป็นจำนวนเต็ม โดยใช้เมธอด int.Parse หรือ Convert.ToInt32 ใน C# หากไม่สามารถแปลงสตริงได้ เมธอด int.Parse หรือ Convert.ToInt32 จะส่งกลับข้อยกเว้น
Convert.ToInt32 อนุญาตค่า Null โดยไม่มีข้อผิดพลาดใด ๆ Int.parse ไม่อนุญาตให้มีค่า Null และแสดงข้อผิดพลาด ArgumentNullException
ตัวอย่าง
class Program {
static void Main() {
int res;
string myStr = "5000";
res = int.Parse(myStr);
Console.WriteLine("Converting String is a numeric representation: " + res);
Console.ReadLine();
}
} ผลลัพธ์
Converting String is a numeric representation: 5000
ตัวอย่าง
class Program {
static void Main() {
int res;
string myStr = null;
res = Convert.ToInt32(myStr);
Console.WriteLine("Converting String is a numeric representation: " + res);
Console.ReadLine();
}
} ผลลัพธ์
Converting String is a numeric representation: 0
ตัวอย่าง
class Program {
static void Main() {
int res;
string myStr = null;
res = int.Parse(myStr);
Console.WriteLine("Converting String is a numeric representation: " + res);
Console.ReadLine();
}
} ผลลัพธ์
Unhandled exception. System.ArgumentNullException: Value cannot be null.