在撰寫日誌、除錯或 AOP 切面時,常需自動取得「呼叫當前方法的方法名稱」。.NET 提供 System.Reflection 與 System.Diagnostics.StackTrace 兩大工具,本文將示範從基本用法到進階堆疊框架分析的完整範例。
using System;
using System.Diagnostics;
using System.Reflection;
MethodBase.GetCurrentMethod() 回傳正在執行的方法資訊。
public static void WriteLog(int level, string content)
{
MethodBase mb = MethodBase.GetCurrentMethod();
var info = $@"模組: {mb.Module}
命名空間: {mb.ReflectedType?.Namespace}
類別完整名稱: {mb.ReflectedType?.FullName}
方法名稱: {mb.Name}";
Console.WriteLine($"LogDate: {DateTime.Now}\nLevel: {level}\n{info}\nContent: {content}\n");
}
使用 StackTrace 取得堆疊框架陣列,索引 1 為呼叫者。
public static void WriteLog(string content)
{
const int level = 1000;
var st = new StackTrace(true); // 捕捉檔案/行號
var frame = st.GetFrame(1); // 0=本方法, 1=呼叫者
var mb = frame.GetMethod();
var info = $@"模組: {mb.Module}
命名空間: {mb.DeclaringType?.Namespace}
類別名稱: {mb.DeclaringType?.Name}
方法名稱: {mb.Name}";
Console.WriteLine($"LogDate: {DateTime.Now}\nLevel: {level}\n{info}\nContent: {content}\n");
}
var st = new StackTrace(true);
foreach (var frame in st.GetFrames())
{
var method = frame.GetMethod();
Console.WriteLine($"{method.DeclaringType?.FullName}.{method.Name}");
}
典型輸出順序:
System.Threading.ThreadHelper.ThreadStart()System.Threading.ExecutionContext.Run(...)Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()System.AppDomain._nExecuteAssembly(...)Main 方法| 屬性 | 說明 |
|---|---|
| Name | 方法名稱 |
| DeclaringType | 宣告該方法的類型 |
| ReflectedType | 透過反射取得的類型(可能為衍生類型) |
| Module | 包含該方法的模組 |
| IsPublic / IsPrivate / IsStatic | 存取修飾詞與靜態判斷 |
| GetParameters() | 取得參數資訊陣列 |
| ReturnType | 回傳型別 |
利用運算式樹或 CallerMemberName 屬性(.NET 4.5+)更優雅:
public void LogValue([CallerMemberName] string name = "", object value = null)
{
Console.WriteLine($"{name} = {value}");
}
// 呼叫
int count = 10;
LogValue(value: count); // 輸出: count = 10
StackTrace 建構較耗效能,避免在高頻熱路徑(如迴圈、每個 Request)大量使用。[MethodImpl(MethodImplOptions.NoInlining)]。SourceContext 自動擷取呼叫類別。掌握 MethodBase.GetCurrentMethod() 與 StackTrace 讓您能建立強大的診斷工具。記住:善用 CallerMemberName、CallerFilePath、CallerLineNumber 屬性(編譯期注入)比執行期反射更高效、更安全。