as Keyword
กนกลักษณ์ นิ่มนวล 650710520
as Keyword
พูดง่ายๆ คือ เมื่อเราต้องการแปลงข้อมูล แต่ไม่แน่ใจว่ามันจะแปลงได้หรือไม่ การใช้ as จะช่วยให้ไม่เกิด error ถ้าแปลงไม่ได้จริงๆ ก็คืนค่า null กลับมา
object obj1 = "as Keyword tutorial";
object obj2 = 520;
string str1 = obj1 as string;
// กรณีที่ 1
if (str1 != null){
Console.WriteLine("obj1 cast Successfully: " + str1);
}else{
Console.WriteLine("obj1 cast Fail");
}
string str2 = obj2 as string;
// กรณีที่ 2
if (str2 != null){
Console.WriteLine("obj2 cast Successfully: " + str2);
}else{
Console.WriteLine("obj2 cast Fail");
}สรุป
Video
Slide Presentation
Reference
Last updated