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

เปรียบเทียบ int.Parse และ int.TryParse ใน C#

int.Parse: แปลงสตริงเป็น int, โยน Exception หากแปลงไม่ได้ (FormatException, ArgumentNullException, OverflowException)

int.TryParse: พยายามแปลง คืน bool (สำเร็จ/ล้มเหลว) และค่าผลลัพธ์ผ่าน out parameter ไม่โยน Exception

ตัวอย่าง int.Parse

string myStr = "120";
int res = int.Parse(myStr); // 120
// หาก myStr = "abc" -> โยน FormatException

ตัวอย่าง int.TryParse

string myStr = "120";
bool res = int.TryParse(myStr, out int a); // res = true, a = 120
// หาก myStr = "abc" -> res = false, a = 0

ผลลัพธ์เปรียบเทียบ

int.Parse: String is a numeric representation: 120
int.TryParse: String is a numeric representation: True

แนวทางปฏิบัติ: ใช้ TryParse สำหรับข้อมูลนำเข้าจากภายนอก (User Input, File, Network) ใช้ Parse เฉพาะเมื่อแน่ใจว่าข้อมูลถูกต้องแล้ว