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

C# 反射操作屬性完整範例:動態賦值與讀取

     編輯:ASP.NET 基礎

核心概念

透過 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),實現通用命令派發、外掛架構等進階用法。

效能提示

  • 反射屬於晚期繫結,效能較直接呼叫低 1~2 數量級。
  • 熱點路徑建議:Delegate.CreateDelegate 快取委派、Expression Tree 編譯 Lambda、或使用原始碼產生器(Source Generator)在編譯期完成映射。
  • 僅在啟動期、配置驅動、動態載入等低頻場合使用反射。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved