2008-12-03 52 views
3

說我有一些這樣的代碼我可以找出我使用的方法的名稱嗎?

namespace Portal 
{ 
    public class Author 
    { 
     public Author() { } 
     private void SomeMethod(){ 
      string myMethodName = ""; 
      // myMethodName = "Portal.Author.SomeMethod()"; 
     } 
    } 
} 

我能找到我使用的方法的名稱?在我的示例中,我想以編程方式將myMethodName設置爲當前方法的名稱(即在此情況下爲"Portal.Author.SomeMethod")。

感謝

回答

14
MethodInfo.GetCurrentMethod().Name 
+0

他快的類型。 =) – StingyJack 2008-12-03 13:30:31

+0

謝謝,正是我需要的東西:D – inspite 2008-12-03 13:31:56

3

System.Reflection.MethodBase.GetCurrentMethod()。名稱

2

MethodBase.GetCurrentMethod()

2

System.DiagnosticsStackFrame/StackTrace它允許你只是,包括更多。您可以檢查整個調用堆棧,像這樣:

StackFrame stackFrame = new StackFrame(1, true); //< skip first frame and capture src info 
StackTrace stackTrace = new StackTrace(stackFrame); 
MethodBase method = stackTrace.GetMethod(); 
string name = method.Name; 
1

雖然@leppie把我在正確的軌道上,它只是給我的方法的名字,但如果你看看我的問題,你會看到,我想包括命名空間和類信息...

所以

myMethodName = System.Reflection.MethodBase.GetCurrentMethod().ReflectedType + 
       "." + System.Reflection.MethodBase.GetCurrentMethod().Name; 
相關問題