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

Reflection trong C#

Reflection cho phép kiểm tra metadata type tại runtime. Namespace: System.Reflection.

Ứng dụng

  • Xem attribute tại runtime
  • Kiểm tra type trong assembly, tạo instance
  • Late binding: gọi method/property qua tên string
  • Tạo type động tại runtime (Reflection.Emit)

Ví dụ: Đọc custom attribute

using System;

[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{
    public readonly string Url;
    public string Topic { get; set; }
    
    public HelpAttribute(string url) { Url = url; }
}

[HelpAttribute("Information on the class MyClass")]
class MyClass { }

namespace AttributeAppl
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Reflection.MemberInfo info = typeof(MyClass);
            object[] attributes = info.GetCustomAttributes(true);
            
            for (int i = 0; i < attributes.Length; i++)
                Console.WriteLine(attributes[i]);
            
            Console.ReadKey();
        }
    }
}

Các class chính

  • Type: trung tâm reflection, typeof(T) hoặc obj.GetType()
  • Assembly: load assembly, get types
  • MethodInfo, PropertyInfo, FieldInfo, ConstructorInfo
  • Activator.CreateInstance: tạo object từ type

Hiệu năng: Reflection chậm hơn code trực tiếp. Cache MethodInfo/PropertyInfo nếu dùng lặp lại. Dùng DynamicMethod hoặc Expression Tree cho performance cao.