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

เมธอด Type.GetTypeHandle() ใน C#

เมธอด Type.GetTypeHandle() ใน C# ใช้ดึงแฮนเดิล (Handle) สำหรับ Type ของออบเจ็กต์ที่ระบุ

ไวยากรณ์

public static RuntimeTypeHandle GetTypeHandle(object ob);

ob คือออบเจ็กต์ที่ต้องการดึงแฮนเดิลของ Type

ตัวอย่างที่ 1: กับ 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: กับ 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) ที่แทนที่อยู่หน่วยความจำของ Type ใช้ร่วมกับ Type.GetTypeFromHandle() เพื่อกลับมาเป็น Type อีกครั้ง