反射允許在執行時動態檢查型別中繼資料。透過 Type.GetProperties() 取得 PropertyInfo 陣列,即可迭代所有**公開且具備 getter/setter** 的屬性,動態讀取或設定值。
public static void DumpProperties(object obj)
{
if (obj == null) throw new ArgumentNullException(nameof(obj));
Type type = obj.GetType();
foreach (PropertyInfo prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (!prop.CanRead) continue; // 僅可寫屬性略過
object value = prop.GetValue(obj, null);
string typeName = prop.PropertyType.Name;
Console.WriteLine($"{prop.Name} ({typeName}) = {value ?? "null"}");
// 依型別進一步處理
if (prop.PropertyType == typeof(int))
{
int intVal = (int)value;
// 業務邏輯...
}
}
}
// ✅ 可被反射讀取
public int Id { get; set; }
// ❌ 無 getter,反射無法讀取
public int Id { set { _id = value; } }
// 含繼承自基底類別的公用實例屬性
var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
this[int index] 也會出現在 GetProperties() 結果中,需以 prop.GetIndexParameters().Length > 0 過濾。
private static readonly ConcurrentDictionary _propCache = new();
public static PropertyInfo[] GetCachedProperties(Type type)
=> _propCache.GetOrAdd(type, t => t.GetProperties(BindingFlags.Public | BindingFlags.Instance));
public static List Diff(object oldObj, object newObj)
{
var diffs = new List();
var props = GetCachedProperties(oldObj.GetType());
foreach (var p in props)
{
var oldVal = p.GetValue(oldObj);
var newVal = p.GetValue(newObj);
if (!Equals(oldVal, newVal))
diffs.Add($"{p.Name}: '{oldVal}' → '{newVal}'");
}
return diffs;
}
var dict = props.ToDictionary(p => p.Name, p => p.GetValue(source));
var expando = new ExpandoObject();
foreach (var kv in dict) ((IDictionary)expando).Add(kv.Key, kv.Value);
反射遍歷屬性是序列化、映射、差異比對、動態 UI 繫結的基石。掌握 BindingFlags、快取策略與例外處理,即能安全高效地運用於生產環境。