2012-07-06 39 views
15

如何在c#中查找調用方法的全名。我已經看到了解決方案:如何查找調用方法C的完整名稱#

How I can get the calling methods in C#

How can I find the method that called the current method?

Get Calling function name from Called function

但他們只給我的最高水平。請看例子:

namespace Sandbox 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      test(); 
     } 

     static void test() 
     { 
      var stackTrace = new StackTrace(); 
      var methodBase = stackTrace.GetFrame(1).GetMethod(); 
      Console.WriteLine(methodBase.Name); 
     } 
    } 
} 

這只是輸出「主」我怎樣才能得到它打印「Sandbox.Program.Main」?

在任何人開始問爲什麼我需要使用它,它爲我正在處理一個簡單的日誌記錄框架。

編輯

添加到Matzi的答案:

這裏是解決方案:

namespace Sandbox 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      test(); 
     } 

     static void test() 
     { 
      var stackTrace = new StackTrace(); 
      var methodBase = stackTrace.GetFrame(1).GetMethod(); 
      var Class = methodBase.ReflectedType; 
      var Namespace = Class.Namespace;   //Added finding the namespace 
      Console.WriteLine(Namespace + "." + Class.Name + "." + methodBase.Name); 
     } 
    } 
} 

產生了 'Sandbox.Program.Main' 像它應該

+1

可能重複[使用的System.Reflection獲取一個方法的全名(http://stackoverflow.com/questions/2968352/using-system-reflection-to-get-a-methods-full -name) – user7116 2012-07-06 18:39:32

回答

27

這事像here

MethodBase method = stackTrace.GetFrame(1).GetMethod(); 
string methodName = method.Name; 
string className = method.ReflectedType.Name; 

Console.WriteLine(className + "." + methodName); 
+0

謝謝!我編輯這個問題只是爲了添加我如何找出命名空間。 – 2012-07-06 18:48:45

+2

不起作用。該方法可能不是調用方法,而是外部調用方法之一 - 調用方法可能不再存在,即已經內聯。 – TomTom 2012-07-06 18:49:41

+0

也有可能獲得嵌套類嗎?如果我在Program中創建了一個類,我們稱之爲'Foo',並且在'Foo'中有一個方法(讓它叫Bar)調用'Program.test()'它應該打印'Sandbox.Program.Foo .Bar' – 2012-07-06 18:56:03

0

System.Reflection.MethodBase方法GetCurrentMethod您可以使用類等找到調用堆棧的完整信息

+0

如何? ['GetCurrentMethod'](https://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod(v = vs.110).aspx)返回['MethodBase'](https:/ /msdn.microsoft.com/en-us/library/system.reflection.methodbase(v=vs.110).aspx),它似乎沒有公開有關堆棧跟蹤(除當前類型)的任何信息。 – c24w 2017-04-07 14:14:29

4

我想拿到全名最好的辦法是:

this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name; 

或試試這個

string method = string.Format("{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name); 
0

用這種方法你可以可靠地得到滿的打着

public void HandleException(Exception ex, [CallerMemberName] string caller = "") 
    { 
     if (ex != null) 
     { 
      while (ex.InnerException != null) 
       ex = ex.InnerException; 

      foreach (var method in new StackTrace().GetFrames()) 
      { 
       if (method.GetMethod().Name == caller) 
       { 
        caller = $"{method.GetMethod().ReflectedType.Name}.{caller}"; 
        break; 
       } 
      } 

      Console.WriteLine($"Exception: {ex.Message} Caller: {caller}()"); 
     } 
    }