萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 反射遍歷物件屬性與值:完整實作指南與進階技巧

核心概念

反射允許在執行時動態檢查型別中繼資料。透過 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;
            // 業務邏輯...
        }
    }
}

關鍵細節與陷阱

1. 必須具備 Get/Set 存取子

// ✅ 可被反射讀取
public int Id { get; set; }

// ❌ 無 getter,反射無法讀取
public int Id { set { _id = value; } }

2. 繼承鏈與 BindingFlags

// 含繼承自基底類別的公用實例屬性
var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);

3. 索引屬性 (Indexer) 會被包含

this[int index] 也會出現在 GetProperties() 結果中,需以 prop.GetIndexParameters().Length > 0 過濾。

4. 效能優化:緩存 PropertyInfo

private static readonly ConcurrentDictionary _propCache = new();

public static PropertyInfo[] GetCachedProperties(Type type)
    => _propCache.GetOrAdd(type, t => t.GetProperties(BindingFlags.Public | BindingFlags.Instance));

進階應用場景

物件差異比對 (Diff)

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;
}

動態建立 DTO / 匿名物件

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、快取策略與例外處理,即能安全高效地運用於生產環境。

copyright © 萬盛學電腦網 all rights reserved