Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ความแตกต่าง int.Parse() และ Convert.ToInt32() ใน C#

ทั้งคู่แปลง String → Int32 แต่ต่างกันที่การจัดการ Null

Convert.ToInt32(null)

คืนค่า 0** ไม่ Throw Exception

string s = null;
int result = Convert.ToInt32(s); // 0

int.Parse(null)

Throw ArgumentNullException

string s = null;
int result = int.Parse(s); // Unhandled Exception: Value cannot be null.

ตัวอย่าง String ที่แปลงได้

string s = "5000";
int r1 = int.Parse(s);        // 5000
int r2 = Convert.ToInt32(s);  // 5000

สรุป

Scenarioint.ParseConvert.ToInt32
Valid Number StringOKOK
NullArgumentNullExceptionReturn 0
Invalid Format (e.g. "abc")FormatExceptionFormatException
OverflowOverflowExceptionOverflowException

แนะนำ

  • ใช้ int.TryParse สำหรับ Validation (Return bool + out int)
  • ใช้ Convert.ToInt32 ถ้าอาจเป็น Null และต้องการ Default 0
  • ใช้ int.Parse ถ้าแน่ใจว่า Not Null และ Valid Format