使用反射來取得呼叫方法資訊
取得呼叫方法的名稱和類型是基於反射的程式設計中的常見需求。當函數執行時,確定呼叫它的上下文非常有用。
使用 StackFrame 類別
一種方法涉及使用 StackFrame 類別。建構函式採用一個整數來表示要檢查的堆疊層級。透過傳遞 1,我們可以檢索有關呼叫方法的資訊。
public class Caller { public void Call() { StackFrame frame = new StackFrame(1); var method = frame.GetMethod(); var type = method.DeclaringType; var name = method.Name; } }
此程式碼會將「Call」指派給 name,將「Caller」指派給 type,假設它是從另一個方法呼叫的。
使用 CallerMemberName屬性
在 .NET 4.5 及更高版本中,CallerMemberNameAttribute 提供了更簡單的解決方案。此屬性將呼叫方法的名稱指定為參數。
public class SomeClass { public void SomeMethod([CallerMemberName]string memberName = "") { Console.WriteLine(memberName); // Output will be the name of the calling method } }
此程式碼會自動將呼叫方法的名稱指派給 memberName 參數,而不需要額外的反射。
以上是C#中如何使用反射來取得呼叫方法資訊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!