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

C# 反射應用實戰(一):核心基礎與 ShowObject 類別完整實作

     編輯:關於C語言

為什麼要學反射?

反射是 C#(及 Java)極具威力的特性。所有主流框架——Struts、Hibernate、Spring、ASP.NET Core、Entity Framework——核心無一不建立在反射之上。它賦予程式「在運行時檢視、操作型別中繼資料」的能力,是動態載入、依賴注入、ORM、插件架構的基石。

領域模型:UserInfo 實體類別

namespace Model
{
    public class UserInfo
    {
        private int userId;
        public int UserId
        {
            get { return userId; }
            set { userId = value; }
        }

        private string userName;
        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }

        public void Show()
        {
            Console.WriteLine("UserId:" + userId + ", UserName:" + userName);
        }
    }
}

核心工具類:ShowObject 完整實作

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ObjectLoader
{
    public class ShowObject
    {
        // 載入包含實體的組件
        private Assembly assembly = Assembly.Load("Model");

        /// 
        /// 依類別名稱(含命名空間)動態建立實例
        /// 
        public object LoadObject(string objName)
        {
            return assembly.CreateInstance("Model." + objName);
        }

        /// 
        /// 取得物件所有公共屬性
        /// 
        public PropertyInfo[] GetPropertys(object obj)
        {
            Type type = obj.GetType();
            return type.GetProperties();
        }

        /// 
        /// 設定指定屬性值
        /// 
        public void SetPropertyValue(object obj, string property, object value)
        {
            Type type = obj.GetType();
            PropertyInfo info = type.GetProperty(property);
            if (info != null)
            {
                info.SetValue(obj, value, null);
            }
        }

        /// 
        /// 取得指定屬性值
        /// 
        public object GetPropertyValue(object obj, string property)
        {
            Type type = obj.GetType();
            PropertyInfo info = type.GetProperty(property);
            if (info == null) return null;
            return info.GetValue(obj, null);
        }

        /// 
        /// 呼叫指定無參方法
        /// 
        public void ExecuteMethod(object obj, string methodName)
        {
            Type type = obj.GetType();
            MethodInfo info = type.GetMethod(methodName);
            if (info != null)
            {
                info.Invoke(obj, null);
            }
        }
    }
}

核心 API 對照表

操作目的關鍵反射類別/方法說明
載入組件Assembly.Load依組件名稱載入至記憶體
建立實例Assembly.CreateInstance依完整型別名稱(含命名空間)建立物件
取得型別資訊obj.GetType() / Type.GetType()反射入口,取得 Type 物件
列舉屬性Type.GetProperties()回傳 PropertyInfo 陣列
設定/取得屬性值PropertyInfo.SetValue / GetValue動態存取屬性,支援私有/公有
呼叫方法Type.GetMethod / MethodInfo.Invoke動態執行實例或靜態方法

效能考量與最佳實務

  • 快取 Type 與 MemberInfo:反射操作較慢,熱路徑應快取 PropertyInfo、MethodInfo
  • 優先使用強型別委派:透過 Delegate.CreateDelegate 將反射轉為強型別委派,大幅提升呼叫效能
  • Source Generator 替代方案:.NET 6+ 可使用原始碼產生器在編譯期完成映射,避免運行時反射

結語

掌握 Assembly、Type、PropertyInfo、MethodInfo 四大核心類別,即掌握反射 80% 的實戰場景。下一篇將展示完整測試驗證流程。

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