ภาพรวม
ใน C# คุณสามารถดึงออบเจ็กต์ Type ที่สอดคล้องกับ RuntimeTypeHandle ได้โดยใช้เมธอด Type.GetTypeFromHandle() วิธีนี้มีประโยชน์เมื่อทำงานกับการอ้างอิงประเภทระดับต่ำ (low-level type references)
ตัวอย่างที่ 1: การใช้กับประเภทพื้นฐาน (short)
using System;
public class Demo
{
public static void Main()
{
Type type1 = typeof(short);
RuntimeTypeHandle typeHandle = Type.GetTypeHandle(type1);
Type type = Type.GetTypeFromHandle(typeHandle);
Console.WriteLine("Attributes = " + type.Attributes);
}
}
ผลลัพธ์
Attributes = AutoLayout, AnsiClass, Class, Serializable, BeforeFieldInit
ตัวอย่างที่ 2: การใช้กับ System.Type
using System;
public class Demo
{
public static void Main()
{
Type type1 = typeof(System.Type);
RuntimeTypeHandle typeHandle = Type.GetTypeHandle(type1);
Type type = Type.GetTypeFromHandle(typeHandle);
Console.WriteLine("Attributes = " + type.Attributes);
}
}
ผลลัพธ์
Attributes = AutoLayout, AnsiClass, Class, Serializable, BeforeFieldInit
คำอธิบายเพิ่มเติม
Type.GetTypeHandle()คืนค่าRuntimeTypeHandleซึ่งเป็นควบคุม (handle) แบบไม่ปลอดภัย (unsafe) ที่แทนประเภทในรันไทม์Type.GetTypeFromHandle()ทำงานย้อนกลับ แปลง handle กลับเป็นออบเจ็กต์Type- คุณสมบัติ
Attributesแสดงแฟล็กเมตาดาต้าของประเภท เช่น การจัดเลย์เอาต์ (layout), ระดับการเข้าถึง (visibility), และพฤติกรรมการเรียงลำดับ (serialization)