ใน C# ทุกอ็อบเจ็กต์สืบทอดมาจาก object ซึ่งมีเมธอด GetType() คืนค่า Type object ที่อธิบายประเภทของอินสแตนซ์ใน runtime (runtime type) ใช้สำหรับ reflection, debugging, serialization, และ type checking
ตัวอย่างโค้ดที่ 1: สตริง
using System;
public class Demo
{
public static void Main()
{
string s = "Demo";
Console.WriteLine("String = " + s);
Console.WriteLine("String Type = " + s.GetType());
}
}
ผลลัพธ์
String = Demo
String Type = System.String
ตัวอย่างโค้ดที่ 2: Primitive Types ต่างๆ
using System;
public class Demo
{
public static void Main()
{
double val1 = 5.5;
int val2 = 10;
short val3 = 2;
Console.WriteLine("Value = " + val1);
Console.WriteLine("Value Type = " + val1.GetType());
Console.WriteLine("Value = " + val2);
Console.WriteLine("Value Type = " + val2.GetType());
Console.WriteLine("Value = " + val3);
Console.WriteLine("Value Type = " + val3.GetType());
}
}
ผลลัพธ์
Value = 5.5
Value Type = System.Double
Value = 10
Value Type = System.Int32
Value = 2
Value Type = System.Int16
ข้อสังเกตสำคัญ
GetType()คืนค่า runtime type (ประเภทจริงของอ็อบเจ็กต์)- ต่างจาก
typeof(T)ที่เป็น compile-time type - สำหรับ value types (int, double, struct) จะเกิด boxing เมื่อเรียก GetType()
- คืนค่า
Typeobject ที่มี metadata เต็มรูปแบบ (name, namespace, assembly, methods, properties, etc.)
การใช้งาน GetType() กับ Polymorphism
using System;
class Animal { }
class Dog : Animal { }
class Cat : Animal { }
public class Demo
{
public static void Main()
{
Animal a1 = new Dog();
Animal a2 = new Cat();
Console.WriteLine(a1.GetType()); // Dog
Console.WriteLine(a2.GetType()); // Cat
Console.WriteLine(typeof(Animal)); // Animal (compile-time)
}
}
เมธอดสำคัญของ Type Class
| Member | คำอธิบาย |
|---|---|
Name | ชื่อประเภท (ไม่มี namespace) |
FullName | ชื่อเต็มพร้อม namespace |
Namespace | namespace |
Assembly | Assembly ที่ประกอบ |
BaseType | คลาสฐาน |
IsClass, IsValueType, IsInterface, IsArray, IsGenericType | ตรวจสอบลักษณะประเภท |
GetMethods(), GetProperties(), GetFields() | Reflection members |
GetConstructor(), GetMethod() | หา constructor/method เฉพาะ |
เคล็ดลับ
- ใช้
obj.GetType() == typeof(MyClass)เพื่อตรวจสอบ exact type - ใช้
obj is MyClassหรือobj as MyClassสำหรับ type checking ทั่วไป (รองรับ inheritance) - ใช้
typeof(T)เมื่อรู้ type ตอน compile-time (เร็วกว่า GetType())