从被调用函数中获取调用函数名称[重复]

时间:2022-03-26 08:26:24

Possible Duplicate:
How can I find the method that called the current method?

可能重复:如何找到调用当前方法的方法?

How can I get the calling function name from the called function in c#?

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

2 个解决方案

#1


72  

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

Note that in release builds the compiler might inline the method being called, in which case the above code would return the caller of the caller, so to be safe you should decorate your method with:

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

[MethodImpl(MethodImplOptions.NoInlining)]

#2


14  

This will get you the name of the method you are in:

这将为您提供您所在方法的名称:

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

Use with caution since there could be a performance hit.

请谨慎使用,因为可能会有性能损失。

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

StackFrame frame = trace.GetFrame(caller);

string callerName = frame.GetMethod().Name;

This uses a stack walk to get the method name. The value of caller is how far up the call stack to go. Be careful not to go to far.

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

#1


72  

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

Note that in release builds the compiler might inline the method being called, in which case the above code would return the caller of the caller, so to be safe you should decorate your method with:

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

[MethodImpl(MethodImplOptions.NoInlining)]

#2


14  

This will get you the name of the method you are in:

这将为您提供您所在方法的名称:

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

Use with caution since there could be a performance hit.

请谨慎使用,因为可能会有性能损失。

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

StackFrame frame = trace.GetFrame(caller);

string callerName = frame.GetMethod().Name;

This uses a stack walk to get the method name. The value of caller is how far up the call stack to go. Be careful not to go to far.

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