从Called函数获取调用函数名称

时间:2009-08-21 04:57:14

标签: c# .net .net-3.5 function

  

可能重复:
  How can I find the method that called the current method?

如何从c#中的被调用函数中获取调用函数名称?

2 个答案:

答案 0 :(得分:74)

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

请注意,在发布版本中,编译器可能会内联被调用的方法,在这种情况下,上面的代码将返回调用者的调用者,因此为了安全起见,您应该用以下方法修饰您的方法:

[MethodImpl(MethodImplOptions.NoInlining)]

答案 1 :(得分: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;

这使用堆栈遍历来获取方法名称。调用者的值是调用栈的距离。小心不要走远。

相关问题