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

Type Casting (การแปลงชนิดข้อมูล) ใน C# คืออะไร

Type casting คือการแปลงชนิดข้อมูลหนึ่งเป็นอีกชนิดหนึ่ง มี 2 รูปแบบ:

  • Implicit type conversion (การแปลงโดยนัย) - C# ทำให้อัตโนมัติอย่างปลอดภัย เช่น แปลงจากชนิดเล็กไปใหญ่ หรือจาก derived class ไป base class
  • Explicit type conversion (การแปลงแสดงเจตนา) - ทำโดยโปรแกรมเมอร์ด้วยฟังก์ชันสำเร็จรูป ต้องใช้ cast operator

เมธอดแปลงชนิดสำเร็จรูป (built-in conversion methods):

No.Method & Description
1ToBoolean - แปลงเป็น Boolean
2ToByte - แปลงเป็น byte
3ToChar - แปลงเป็น Unicode character
4ToDateTime - แปลงเป็นโครงสร้างวันที่-เวลา
5ToDecimal - แปลงเป็น decimal
6ToDouble - แปลงเป็น double

ตัวอย่าง: แปลง int เป็น string

using System;

namespace Demo {
    class Program {
        static void Main(string[] args) {
            int i = 20;
            Console.WriteLine(i.ToString());
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

20