反射是執行期動態取得型別資訊的機制:列舉屬性、方法、建構函式、委派等,甚至動態呼叫方法、存取屬性值。核心命名空間 System.Reflection。
自製 ORM 採「Attribute 定義映射規則 + 反射動態讀取」架構。因實體類別獨立於 ORM 框架,框架無法預知類別結構,必須透過反射在執行期掃描 Attribute,動態建構 SQL。
以 Person 類別(Name、Age、Sex 三屬性)為例,動態讀取屬性值:
public class Person {
private string _name; private int _age; private string _sex;
public string Name { get => _name; set => _name = value; }
public int Age { get => _age; set => _age = value; }
public string Sex { get => _sex; set => _sex = value; }
}
// 使用反射取得屬性值
Person p = new Person { Name = "Tom", Age = 30, Sex = "M" };
PropertyInfo[] props = p.GetType().GetProperties();
foreach (var prop in props) {
Console.WriteLine($"{prop.Name} = {prop.GetValue(p)}");
}
輸出:
Name = Tom
Age = 30
Sex = M
此為後續動態構建 INSERT/UPDATE/DELETE 語句的基石。