使用反射必須引入 System.Reflection 命名空間。該命名空間提供動態載入組件、型別,動態呼叫方法、設定與取得屬性與欄位值,以及取得型別與方法資訊的功能。
若要對型別實例的屬性或欄位進行動態賦值或取值,首先必須取得該實例或型別的 Type 物件。常見方式有二:
// 方式一:從型別直接取得
Type t = typeof(MyClass);
// 方式二:從實例取得
MyClass myObj = new MyClass();
Type t = myObj.GetType();
取得 Type 後,即可透過 GetProperty 取得 PropertyInfo,再呼叫 SetValue / GetValue:
// 設定屬性值
t.GetProperty("Field").SetValue(myObj, 1, null);
// 取得屬性值
int propValue = Convert.ToInt32(t.GetProperty("Field").GetValue(myObj, null));
若將屬性名與值寫入設定檔,即可實現執行期動態設定屬性。
使用反射動態呼叫類別成員,核心方法為 Type.InvokeMember,其宣告如下:
public object InvokeMember(
string name,
BindingFlags invokeAttr,
Binder binder,
object target,
object[] args
);
後續文章將詳細說明各參數與 BindingFlags 的使用細節。