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

Ứng dụng của Reflection (Phản chiếu) trong C#

Reflection (Phản chiếu) cho phép chương trình kiểm tra, phân tích và thao tác với metadata của assembly, type, member tại runtime. Các lớp nằm trong namespace System.Reflection.

4 Ứng dụng chính

  1. Xem thông tin Attribute tại runtime: Đọc custom attributes gắn trên class, property, method...
  2. Khám phá và tạo instance type động: Assembly.Load(), Activator.CreateInstance(), plugin system.
  3. Late Binding (Gọi muộn): Gọi method/property qua tên chuỗi tại runtime (MethodInfo.Invoke()).
  4. Tạo kiểu động (Dynamic Type Creation): System.Reflection.Emit tạo assembly, module, type tại runtime.

Ví dụ: Đọc Custom Attribute

using System;
using System.Reflection;

// Custom Attribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HelpAttribute : Attribute
{
    public string Url { get; }
    public string Topic { get; set; }
    
    public HelpAttribute(string url) => Url = url;
}

// Áp dụng attribute
[HelpAttribute("https://docs.example.com/MyClass", Topic = "Getting Started")]
public class MyClass
{
    [HelpAttribute("https://docs.example.com/MyClass/DoWork")]
    public void DoWork() { }
}

class Program
{
    static void Main()
    {
        // Lấy MemberInfo của class
        MemberInfo info = typeof(MyClass);
        
        // Lấy tất cả custom attributes
        object[] attrs = info.GetCustomAttributes(true);
        
        Console.WriteLine($"Attributes trên {info.Name}:");
        foreach (Attribute attr in attrs)
        {
            if (attr is HelpAttribute help)
                Console.WriteLine($"  - Help: {help.Url}, Topic: {help.Topic}");
        }
        
        // Lấy attribute trên method
        MethodInfo method = typeof(MyClass).GetMethod("DoWork");
        var methodAttrs = method.GetCustomAttributes(true);
        foreach (var ma in methodAttrs)
            Console.WriteLine($"  Method DoWork: {ma.Url}");
        
        Console.ReadKey();
    }
}

Kết quả

Attributes trên MyClass:
  - Help: https://docs.example.com/MyClass, Topic: Getting Started
  Method DoWork: https://docs.example.com/MyClass/DoWork

Các lớp Reflection quan trọng

LớpMục đích
AssemblyTải, kiểm tra assembly (.dll/.exe)
TypeThông tin kiểu: tên, namespace, base class, interface, member...
MemberInfo (base)Base class cho FieldInfo, PropertyInfo, MethodInfo, ConstructorInfo, EventInfo
MethodInfoGọi method động: Invoke(obj, args)
PropertyInfoĐọc/ghi property động: GetValue, SetValue
ActivatorTạo instance: CreateInstance<T>(), CreateInstance(type)

Cảnh báo hiệu năng

  • Reflection chậm hơn gọi trực tiếp (overhead lookup, validation).
  • Cache MethodInfo, PropertyInfo nếu gọi lặp lại.
  • Cân nhắc dynamic (DLR) hoặc Source Generators cho performance critical.