首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

C# Reflection 實戰:動態 Get/Set 類別屬性值完整範例

     編輯:ASP.NET 基礎

反射(Reflection)讓程式在執行期檢查、實例化、呼叫類型成員。本文以 Member 類別的 Name 屬性為例,示範如何透過 PropertyInfo 動態設定與讀取屬性值,包含 BindingFlags 過濾公開實例屬性、CanWrite/CanRead 防護檢查。

目標類別

public class Member {
    private string _Name;
    public string Name { get => _Name; set => _Name = value; }
}

反射操作步驟

  1. Type type = obj.GetType(); 取得型別資訊
  2. PropertyInfo pi = type.GetProperty("Name", BindingFlags.Public | BindingFlags.Instance); 取得屬性元資料
  3. Set:if (pi != null && pi.CanWrite) pi.SetValue(obj, "Insus.NET", null);
  4. Get: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());

進階應用場景

  • 物件對映(AutoMapper 內部原理)
  • 動態表單驗證、序列化
  • 外掛架構:掃描組件載入實作特定介面的類別
  • 單元測試:存取 private 欄位/方法

效能提醒

反射比直接呼叫慢數十倍,高頻呼叫處建議:

  • 緩存 PropertyInfo 陣列/字典
  • 使用 Delegate.CreateDelegate 或 Expression Tree 編譯為強型別委派
  • .NET Core 3.0+ 可用 System.Text.Json 內建反射快取

本例為反射入門基石,掌握 Type、PropertyInfo、MethodInfo 三大核心類別即可應對大多數動態型別操作需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved