反射(Reflection)讓程式在執行期檢查、實例化、呼叫類型成員。本文以 Member 類別的 Name 屬性為例,示範如何透過 PropertyInfo 動態設定與讀取屬性值,包含 BindingFlags 過濾公開實例屬性、CanWrite/CanRead 防護檢查。
public class Member {
private string _Name;
public string Name { get => _Name; set => _Name = value; }
}
Type type = obj.GetType(); 取得型別資訊PropertyInfo pi = type.GetProperty("Name", BindingFlags.Public | BindingFlags.Instance); 取得屬性元資料if (pi != null && pi.CanWrite) pi.SetValue(obj, "Insus.NET", null);if (pi != null && pi.CanRead) object val = pi.GetValue(obj, null);Member obj = new Member();
PropertyInfo pi = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if (pi != null && pi.CanWrite) pi.SetValue(obj, "Insus.NET", null);
PropertyInfo pi2 = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if (pi2 != null && pi2.CanRead) Response.Write(pi2.GetValue(obj, null).ToString());
反射比直接呼叫慢數十倍,高頻呼叫處建議:
PropertyInfo 陣列/字典Delegate.CreateDelegate 或 Expression Tree 編譯為強型別委派System.Text.Json 內建反射快取本例為反射入門基石,掌握 Type、PropertyInfo、MethodInfo 三大核心類別即可應對大多數動態型別操作需求。