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

การดึง RuntimeTypeHandle ของ Type ที่ระบุใน C#

ภาพรวม

Type.GetTypeHandle(Type type) คืนค่า RuntimeTypeHandle ซึ่งเป็น handle ภายใน runtime สำหรับ Type นั้น สามารถนำกลับมาเป็น Type ได้ด้วย Type.GetTypeFromHandle()

ตัวอย่างที่ 1: ดึง Handle ของ 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);
        Console.WriteLine("Type Referenced = " + type);
    }
}

ผลลัพธ์

Attributes = AutoLayout, AnsiClass, Class, Serializable, BeforeFieldInit
Type Referenced = System.RuntimeType

ตัวอย่างที่ 2: ดึง Handle ของ double

using System;

public class Demo
{
    public static void Main()
    {
        Type type1 = typeof(double);
        RuntimeTypeHandle typeHandle = Type.GetTypeHandle(type1);
        Type type = Type.GetTypeFromHandle(typeHandle);

        Console.WriteLine("Attributes = " + type.Attributes);
        Console.WriteLine("Type Referenced = " + type);
    }
}

ผลลัพธ์

Attributes = AutoLayout, AnsiClass, Class, Serializable, BeforeFieldInit
Type Referenced = System.RuntimeType

สรุป

  • RuntimeTypeHandle เป็น struct เบา นำไปใช้กับ interop หรือ low-level APIs
  • GetTypeFromHandle() แปลงกลับเป็น Type object
  • Attributes แสดงลักษณะของ type (class, serializable, layout, etc.)
  • ไม่ควรใช้แทน typeof() ในโค้ดทั่วไป