C# 从被调用函数中获取调用函数名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1310145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:58:33  来源:igfitidea点击:

Get Calling function name from Called function

c#.net.net-3.5function

提问by Sauron

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# 中的被调用函数中获取调用函数名称?

采纳答案by Ben M

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)]

回答by Joe Caffeine

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.

这使用堆栈遍历来获取方法名称。caller 的值是调用堆栈向上走多远。注意不要走远。