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
- Xem thông tin Attribute tại runtime: Đọc custom attributes gắn trên class, property, method...
- Khám phá và tạo instance type động:
Assembly.Load(),Activator.CreateInstance(), plugin system. - Late Binding (Gọi muộn): Gọi method/property qua tên chuỗi tại runtime (
MethodInfo.Invoke()). - Tạo kiểu động (Dynamic Type Creation):
System.Reflection.Emittạ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ớp | Mục đích |
|---|---|
Assembly | Tải, kiểm tra assembly (.dll/.exe) |
Type | Thông tin kiểu: tên, namespace, base class, interface, member... |
MemberInfo (base) | Base class cho FieldInfo, PropertyInfo, MethodInfo, ConstructorInfo, EventInfo |
MethodInfo | Gọi method động: Invoke(obj, args) |
PropertyInfo | Đọc/ghi property động: GetValue, SetValue |
Activator | Tạ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,PropertyInfonếu gọi lặp lại. - Cân nhắc
dynamic(DLR) hoặc Source Generators cho performance critical.