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

Lấy kiểu được tham chiếu bởi handle kiểu cụ thể trong C#

Giới thiệu

Trong C#, bạn có thể lấy đối tượng Type đại diện cho một kiểu dữ liệu từ RuntimeTypeHandle bằng phương thức Type.GetTypeFromHandle(). Điều này hữu ích khi làm việc với phản chiếu (reflection) hoặc khi cần thao tác với kiểu dữ liệu ở mức độ thấp.

Ví dụ 1: Lấy kiểu từ handle của kiểu nguyên thủy

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

Kết quả

Attributes = AutoLayout, AnsiClass, Class, Serializable, BeforeFieldInit

Ví dụ 2: Lấy kiểu từ handle của 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);
    }
}

Kết quả

Attributes = AutoLayout, AnsiClass, Class, Serializable, BeforeFieldInit

Giải thích

  • typeof(short) lấy đối tượng Type cho kiểu short.
  • Type.GetTypeHandle() trả về RuntimeTypeHandle - một giá trị trỏ đến metadata của kiểu trong runtime.
  • Type.GetTypeFromHandle() chuyển ngược lại từ handle sang đối tượng Type.
  • Thuộc tính Attributes hiển thị các flag metadata của kiểu (layout tự động, lớp ANSI, có thể tuần tự hóa, khởi tạo trước trường, v.v.).