2009-08-21 158 views
32

可能重复:
How can I find the method that called the current method?获取从调用函数调用函数名

我怎样才能从C#调用函数调用函数的名字吗?

+1

重复http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-c​​alled-the-current-method – 2009-08-21 05:00:02

+2

这是一个骗局,但可能值得保持开放到不同的术语 - 可能有助于搜索人员。 – Keith 2009-08-21 13:27:08

+1

@Keith:是的,出于这个原因,我们通常会尽量避免重复问题,当他们以一种截然不同的方式被问到 - 这就是为什么关闭它们会自动在顶部添加链接的原因,以便未来的搜索者可以找到方法答案更快。 – Shog9 2009-08-21 18:28:08

回答

70
new StackFrame(1, true).GetMethod().Name 

注意,在发布版本的编译器可能会内联该方法被调用,在这种情况下,上面的代码将返回调用程序的调用程序,因此为了安全起见你应该装点你的方法:

[MethodImpl(MethodImplOptions.NoInlining)] 
+11

请注意,以这种方式走栈会带来相当重的性能影响。我强烈建议在使用之前寻找一种不涉及堆栈散步的解决方案。 – jrista 2009-08-21 05:01:12

+1

由于提到了MethodImpl属性,所以此答案实际上比重复问题中的答案要好。 – 2009-08-29 16:35:33

+8

我知道这是一个骗局,标签为.net 3.5,但为了帮助那些第一次遇到这种情况的人(像我一样),最好在你的回答中指出,在C#5.0中你现在可以使用所描述的调用者信息在:http://visualstudiomagazine.com/articles/2012/11/01/more-than-just-async.aspx – acarlon 2013-09-13 02:46:28

14

这将让你,你是在方法的名字:

string currentMethod = System.Reflection.MethodBase.GetCurrentMethod().Name; 

使用谨慎,因为有可能是一个性能命中。

To get callers: 
StackTrace trace = new StackTrace(); 
int caller = 1; 

StackFrame frame = trace.GetFrame(caller); 

string callerName = frame.GetMethod().Name; 

这使用堆栈散步来获取方法名称。调用者的价值是调用堆栈走多远。小心不要走远。

+0

我需要哪个方法调用当前的方法。 – Sauron 2009-08-21 05:11:57

+0

您从堆栈跟踪中获取调用者名称的方式,是否会影响性能? – Panos 2014-10-29 13:33:46