Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy handle Type của object chỉ định trong C#

Để lấy handle cho Type của một object chỉ định, ta dùng Type.GetTypeHandle và Type.GetTypeFromHandle. Dưới đây là các ví dụ.

Ví dụ 1

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);
    }
}

Kết quả

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

Ví dụ 2

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);
    }
}

Kết quả

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