透過 Type.GetProperties() 取得 PropertyInfo 集合,配合 SetValue/GetValue 即可在執行期動態存取物件屬性,適用於通用實體映射、序列化、表單繫結等場景。
public class MyClass
{
public int One { get; set; }
public int Two { get; set; }
public int Three { get; set; }
public int Four { get; set; }
public int Five { get; set; }
}
var obj = new MyClass();
Type t = typeof(MyClass);
// 1. 迴圈依序賦值 0,1,2,3,4
int i = 0;
foreach (var prop in t.GetProperties())
{
prop.SetValue(obj, i++, null);
}
// 2. 指定屬性單獨賦值
t.GetProperty("Five").SetValue(obj, 11111111, null);
// 3. 迴圈讀取所有屬性值
var sb = new StringBuilder();
foreach (var prop in t.GetProperties())
{
sb.AppendFormat("型別:{0} 屬性:{1} 值:{2}<br />",
prop.PropertyType.FullName, prop.Name, prop.GetValue(obj, null));
}
// 4. 單獨讀取指定屬性
int five = Convert.ToInt32(t.GetProperty("Five").GetValue(obj, null));
sb.Append("單獨取 Five 值:" + five);
Response.Write(sb.ToString());
型別:System.Int32 屬性:One 值:0 型別:System.Int32 屬性:Two 值:1 型別:System.Int32 屬性:Five 值:11111111 型別:System.Int32 屬性:Three 值:3 型別:System.Int32 屬性:Four 值:4 單獨取 Five 值:11111111
同理,將 GetProperties() 改為 GetMethods(),取得 MethodInfo 後即可動態呼叫 Invoke(obj, parameters),實現通用命令派發、外掛架構等進階用法。
Delegate.CreateDelegate 快取委派、Expression Tree 編譯 Lambda、或使用原始碼產生器(Source Generator)在編譯期完成映射。