2009-01-07 111 views

回答

0

看到這個問題:
Can you use reflection to find the name of the currently executing method?

這不是一個重複的,但這個問題的答案會回答你爲好。

+1

不是真的 - 因爲雖然這是可行的獲取調用方法,不告訴你實際的類型進行調用的對象。例如,它可以在BaseClass.Foo()中,但是來自DerivedClass的一個實例,它實現了Andrew正在尋找的接口。 – 2009-01-07 14:51:18

+0

它確實會給你一個堆棧跟蹤。 – 2009-01-07 14:53:34

18

沒有,沒有 - 至少在沒有使用的一些描述一個剖析/調試API。您可以走棧看看方法,但要注意的是,由於JIT優化,它非常慢並且可能不準確。這不會告訴你什麼叫對象雖然(如果確實有一個)。

2

如果你想你可以試試這個類型:

新的StackFrame(1).GetMethod()DeclaringType

正如喬恩指出,如果碰上JIT optimisizations可能存在的問題。

至於從對象中獲取數據,我不認爲這是可能的。

編輯

只是爲了闡述的優化問題,採取以下代碼:

class stackTest 
    { 
     public void Test() 
     { 
      StackFrame sFrame = new StackFrame(1); 
      if (sFrame == null) 
      { 
       Console.WriteLine("sFrame is null"); 
       return; 
      } 

      var method = sFrame.GetMethod(); 

      if (method == null) 
      { 
       Console.WriteLine("method is null"); 
       return; 
      } 
      Type declaringType = method.DeclaringType; 
      Console.WriteLine(declaringType.Name); 
     } 

     public void Test2() 
     { 
      Console.WriteLine(new StackFrame(1).GetMethod().DeclaringType.Name); 
     } 
    } 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      stackTest s = new stackTest(); 
      s.Test(); 
      Console.WriteLine("Doing Test2"); 
      s.Test2(); 
      Console.ReadLine(); 

     } 
    } 

我們應該計劃到控制檯兩次,當您在執行調試器中運行。當你在沒有調試器的情況下運行時,你會得到第一個測試函數的輸出。這可能是因爲內聯需要很複雜;但是,第二種方法會導致空引用異常。

與此代碼的另一種危險是,在MS提高了JIT編譯器什麼可能在2.0已經可以工作和好如初在未來的版本。

相關問題