在開發外掛系統、動態代理、API 文件產生器或測試框架時,常需要在執行時期檢視類別的公開方法。C# 的反射機制(System.Reflection)提供完整的型別中繼資料存取能力。
using System;
using System.Reflection;
public string[] GetMethodList(Type type)
{
// 取得宣告於此類別的公開實例方法(不含繼承)
MethodInfo[] methods = type.GetMethods(
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
string[] names = new string[methods.Length];
for (int i = 0; i < methods.Length; i++)
{
names[i] = methods[i].Name;
}
return names;
}
| 旗標 | 用途 |
|---|---|
Public | 包含 public 方法 |
Instance | 包含實例方法(非 static) |
DeclaredOnly | 僅包含直接宣告於此類別的成員,排除繼承自基底類別的成員 |
Static | 包含靜態方法 |
NonPublic | 包含 private/protected 方法 |
FlattenHierarchy | 包含繼承鏈上的靜態成員 |
MethodInfo[] allPublic = type.GetMethods(BindingFlags.Public | BindingFlags.Instance);
public string[] GetMethodSignatures(Type type)
{
return type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.Select(m => $"{m.ReturnType.Name} {m.Name}({string.Join(", ", m.GetParameters().Select(p => $"{p.ParameterType.Name} {p.Name}"))})")
.ToArray();
}
var apiMethods = type.GetMethods()
.Where(m => m.GetCustomAttribute() != null)
.ToArray();
MethodInfo[] 結果Delegate.CreateDelegate 或 Expression 樹建立強型別委派System.Text.Json 原始碼產生器避免反射序列化using System;
using System.Reflection;
class Demo
{
public void MethodA() { }
public int MethodB(string s) => s.Length;
private void InternalMethod() { }
static void Main()
{
var list = GetMethodList(typeof(Demo));
foreach (var name in list)
Console.WriteLine(name);
// 輸出:
// MethodA
// MethodB
}
static string[] GetMethodList(Type t) =>
t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.Select(m => m.Name)
.ToArray();
}