as Keyword
กนกลักษณ์ นิ่มนวล 650710520
as Keyword
as Keyword ใน C# ใช้สำหรับแปลงข้อมูลชนิดหนึ่งไปเป็นอีกชนิดหนึ่ง ถ้าแปลงได้สำเร็จก็จะคืนค่ากลับมา แต่ถ้าแปลงไม่ได้ก็จะส่งค่า null
พูดง่ายๆ คือ เมื่อเราต้องการแปลงข้อมูล แต่ไม่แน่ใจว่ามันจะแปลงได้หรือไม่ การใช้ as จะช่วยให้ไม่เกิด error ถ้าแปลงไม่ได้จริงๆ ก็คืนค่า null กลับมา
ในกรณีที่ obj1 ที่เก็บข้อมูลแบบ string เลยใช้ as แปลงเป็น string ได้สำเร็จ เพราะเป็นข้อมูลชนิดเกียวกันอยู่แล้ว ส่วนในกรณี obj2 ที่เก็บข้อมูลแบบ int จะใช้ as แปลงเป็น string ไม่สำเร็จ เพราะข้อมูลเป็นคนละชนิดกัน ทำให้ as คืนค่า null กลับมา
แม้ว่าใน Java และ Python จะไม่มี as keyword เหมือนใน C# แต่ Java และ Python ก็มีการแปลงชนิดข้อมูลและการใช้งานก็เหมือนกับ as keyword ใน C#
ใน Java ไม่มี as Keyword เหมือนใน C# แต่สามารถใช้ instanceof เพื่อตรวจสอบชนิดข้อมูลของตัวแปรก่อนที่จะทำการ casting ซึ่งการใช้ instanceof จะคืนค่าเป็น boolean จะคืนค่า true หากชนิดข้อมูลตรงกัน และจะคืนค่า false หากชนิดข้อมูลไม่ตรงกัน
ใน Python ไม่มี as Keyword เหมือนใน C# แต่เราสามารถใช้ isinstance() ในการเช็คว่าข้อมูลเป็นชนิดที่ตรงตามที่เราต้องการแปลงหรือไม่ โดย isinstane() จะคืนค่าเป็น boolean เช่นเดียวกับใน Java
สรุป
C# ใช้ as Keyword ในการแปลงชนิดข้อมูล และจะคืนค่า null หากแปลงไม่สำเร็จ
Java ใช้ instanceof จะคืนค่าเป็น boolean เพื่อตรวจสอบชนิดข้อมูลก่อนแปลง
Python ใช้ฟังก์ชัน isnstance() จะคืนค่าเป็น boolean เพื่อตรวจสอบชนิดข้อมูลก่อนแปลง
Video
Slide Presentation
Reference
GeeksforGeeks. (2022, August 23). C# as Operator Keyword. Retrieved from https://www.geeksforgeeks.org/c-sharp-as-operator-keyword/ นำมาใช้เพื่อศึกษาความหมายของ as Operator Keyword
Microsoft. (n.d.). As operator. Retrieved from https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast#as-operatorนำมาใช้เพื่อศึกษาความหมายของ as Operator Keyword และศึกษาการใช้ as ในการเขียนโค้ดเพิ่มเติม
Harness. (2020, May 10). C# vs Java: 5 Key Differences You Should Know. Retrieved from https://www.harness.io/blog/c-vs-java-5 นำเอาหัวข้อที่5 หัวข้อเปรียบเทีบ as keyword ใน C# กับใน Java
W3Schools. (n.d.). Java Type Casting. Retrieved October 15, 2024, Retrieved from https://www.w3schools.com/java/java_type_casting.asp นำเอาวิธีการทำ Type Casting ใน Java มาใช้
W3Schools. (n.d.). Java instanceof Keyword. Retrieved October 15, 2024, Retrieved from https://www.w3schools.com/java/ref_keyword_instanceof.asp นำเอาคำสั่ง instanceof in Java มาใช้
Sling Academy. (February 17, 2024). Type Casting in Python. Retrieved from https://www.slingacademy.com/article/type-casting-in-python-the-ultimate-guide-with-examples/ นำเอาการ type casting ใน Python มาใช้ในการศึกษาเขียนโค้ด
W3Schools. (n.d.). Python isinstance() Function. Retrieved from https://www.w3schools.com/python/ref_func_isinstance.asp นำเอา ฟังก์ชัน isinstance() in Python มาใช้ในการศึกษาเขียนโค้ดเพิ่มเติม
Last updated