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

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

เมธอด Type.GetTypeFromHandle() ใน C# ใช้ดึง Type ที่ถูกอ้างอิงโดยแฮนเดิลประเภท (RuntimeTypeHandle) ที่ระบุ

ไวยากรณ์

public static Type GetTypeFromHandle(RuntimeTypeHandle handle);

handle คือออบเจ็กต์ที่อ้างอิงถึง Type

ตัวอย่างที่ 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

ความสัมพันธ์: GetTypeHandle() และ GetTypeFromHandle() เป็นคู่กัน — ตัวแรกแปลง Type เป็น Handle ตัวหลังแปลง Handle กลับเป็น Type