反射讓程序在**運行時**檢查、實例化、調用未知類型的成員。核心入口是 System.Type,它封裝了類型的完整元數據:方法、屬性、字段、構造函數、特性、泛型參數等。
// 1. 編譯期已知類型
Type t1 = typeof(MyClass);
Type t2 = typeof(List);
// 2. 實例獲取
MyClass obj = new MyClass();
Type t3 = obj.GetType();
// 3. 字符串名稱動態加載(需完整限定名)
Type t4 = Type.GetType("MyNamespace.MyClass, MyAssembly");
Type t5 = Assembly.Load("MyAssembly").GetType("MyNamespace.MyClass");
| 需求 | API | 返回類型 |
|---|---|---|
| 所有公共方法 | GetMethods() | MethodInfo[] |
| 指定綁定標記 | GetMethods(BindingFlags) | MethodInfo[] |
| 所有公共屬性 | GetProperties() | PropertyInfo[] |
| 所有公共字段 | GetFields() | FieldInfo[] |
| 構造函數 | GetConstructors() | ConstructorInfo[] |
| 自定義特性 | GetCustomAttributes() | object[] |
// 僅獲取當前類聲明的公共實例方法(排除繼承自 Object)
var methods = t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
// 獲取私有靜態字段
var fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Static);
常用標記:Public/NonPublic、Instance/Static、DeclaredOnly(不含繼承)、FlattenHierarchy(含靜態繼承)。
MethodInfo mi = t.GetMethod("MethodName");object[] args = { arg1, arg2 };(無參傳 null 或 Array.Empty<object>())。object result = mi.Invoke(instance, args);(靜態方法 instance = null)。
using System;
using System.Reflection;
class MyClass {
public int X { get; set; }
public int Y { get; set; }
public MyClass(int x, int y) { X = x; Y = y; }
public int Sum() => X + Y;
public bool IsBetween(int v) => X < v && v < Y;
public void Set(int x, int y) { X = x; Y = y; }
public void Show() => Console.WriteLine($"X:{X}, Y:{Y}");
}
class Program {
static void Main() {
Type t = typeof(MyClass);
Console.WriteLine($"類型: {t.FullName}");
// 1. 列舉方法
foreach (var m in t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)) {
Console.Write($"{m.ReturnType.Name} {m.Name}(");
var ps = m.GetParameters();
for (int i = 0; i < ps.Length; i++) {
if (i > 0) Console.Write(", ");
Console.Write($"{ps[i].ParameterType.Name} {ps[i].Name}");
}
Console.WriteLine(")");
}
// 2. 動態創建實例並調用
var instance = Activator.CreateInstance(t, 10, 20); // 調用構造函數
var sumMi = t.GetMethod("Sum");
int sum = (int)sumMi.Invoke(instance, null);
Console.WriteLine($"Sum = {sum}");
var setMi = t.GetMethod("Set");
setMi.Invoke(instance, new object[] { 5, 15 });
var showMi = t.GetMethod("Show");
showMi.Invoke(instance, null); // 輸出 X:5, Y:15
}
}
GetMethod/Invoke 有顯著開銷(委托調用慢 10-100 倍)。MethodInfo/PropertyInfo,或編譯為 Delegate/Expression 樹。System.Reflection.Emit、DynamicMethod 或源生成器。| 場景 | 推薦方案 | 優勢 |
|---|---|---|
| 配置綁定 | Microsoft.Extensions.Configuration.Binder | 聲明式、高性能、支持驗證 |
| 依賴注入 | 內置 DI 容器 | 生命周期管理、攔截、AOP |
| 動態代理 | DispatchProxy / Castle DynamicProxy | 接口級攔截,無反射調用開銷 |
| JSON 序列化 | System.Text.Json (Source Generator) | 編譯期生成,零反射 |
| 插件系統 | AssemblyLoadContext + 接口契約 | 隔離卸載、類型安全 |
BindingFlags.NonPublic),**沙箱環境需限制 ReflectionPermission**。RuntimeFeature.IsDynamicCodeSupported 檢測平台能力。反射是「元編程的瑞士軍刀」,賦予 C# 動態語言般的靈活性。**掌握 Type/MethodInfo/PropertyInfo 三大核心、BindingFlags 精準篩選、Invoke 動態調用** 是基礎;**生產環境必須緩存元數據、評估性能開銷、優先考慮聲明式替代方案**。源生成器與 AOT 編譯趨勢下,運行期反射正逐步被編譯期元編程取代,但理解其原理仍是高級開發者必修內功。