2012-07-06 60 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}()"); 
     } 
    }