反射讓程序在運行時檢查、修改自身結構與行為。核心命名空間 System.Reflection,核心類型 Type。
| 優點 | 缺點 |
|---|---|
| 極高靈活性、擴展性、解耦 | 性能顯著低於直接調用(解釋操作) |
| 無需硬編碼目標類型 | 模糊程序邏輯,維護困難,代碼複雜 |
| 框架級開發必備(DI、ORM、序列化) | 普通業務代碼不建議使用 |
System.Reflection.Emit)[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : Attribute {
public string Url { get; }
public string Topic { get; set; }
public HelpAttribute(string url) => Url = url;
}
[HelpAttribute("Info", Topic="Class")]
class MyClass {}
// 反射讀取
var info = typeof(MyClass);
var attrs = info.GetCustomAttributes(true);
foreach (var a in attrs) Console.WriteLine(a); // HelpAttribute
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method, AllowMultiple=true)]
public class DeBugInfo : Attribute {
public int BugNo { get; }
public string Developer { get; }
public string LastReview { get; }
public string Message { get; set; }
public DeBugInfo(int no, string dev, string review) { ... }
}
[DeBugInfo(45, "Zara", "12/8/2012", Message="Return mismatch")]
class Rectangle { ... }
// 掃描類與方法屬性
var type = typeof(Rectangle);
foreach (var attr in type.GetCustomAttributes(false)) { ... }
foreach (var method in type.GetMethods()) {
foreach (var attr in method.GetCustomAttributes(true)) { ... }
}
輸出包含類級、方法級所有 DeBugInfo 記錄。