當需要動態取得物件中巢狀物件(如 RootObject)的所有屬性值時,可透過反射分兩步驟完成:先取得欄位,再遍歷屬性。
public static void GetProperties(object obj, string memberName)
{
Type type = obj.GetType();
FieldInfo field = null;
if (memberName == "RootObject")
{
field = type.GetField("rootObject");
}
object subObj = field.GetValue(obj);
Type subType = subObj.GetType();
foreach (PropertyInfo prop in subType.GetProperties())
{
Console.WriteLine("{0}: {1}", prop.Name, prop.GetValue(subObj, null));
}
}
type.GetField("rootObject"):取得外層類別中名為 rootObject 的欄位(非屬性)。field.GetValue(obj):從實例 obj 中取出該欄位的值(即內層物件)。subType.GetProperties():取得內層物件所有公開屬性。private,需加 BindingFlags.NonPublic | BindingFlags.Instance。GetValue 參數需調整。此模式適用於任何「物件屬性為另一物件」的動態檢視需求。