反射是 C#(及 Java)極具威力的特性。所有主流框架——Struts、Hibernate、Spring、ASP.NET Core、Entity Framework——核心無一不建立在反射之上。它賦予程式「在運行時檢視、操作型別中繼資料」的能力,是動態載入、依賴注入、ORM、插件架構的基石。
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);
}
}
}
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);
}
}
}
}
| 操作目的 | 關鍵反射類別/方法 | 說明 |
|---|---|---|
| 載入組件 | Assembly.Load | 依組件名稱載入至記憶體 |
| 建立實例 | Assembly.CreateInstance | 依完整型別名稱(含命名空間)建立物件 |
| 取得型別資訊 | obj.GetType() / Type.GetType() | 反射入口,取得 Type 物件 |
| 列舉屬性 | Type.GetProperties() | 回傳 PropertyInfo 陣列 |
| 設定/取得屬性值 | PropertyInfo.SetValue / GetValue | 動態存取屬性,支援私有/公有 |
| 呼叫方法 | Type.GetMethod / MethodInfo.Invoke | 動態執行實例或靜態方法 |
PropertyInfo、MethodInfoDelegate.CreateDelegate 將反射轉為強型別委派,大幅提升呼叫效能掌握 Assembly、Type、PropertyInfo、MethodInfo 四大核心類別,即掌握反射 80% 的實戰場景。下一篇將展示完整測試驗證流程。