C# 方法调用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1163435/
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 09:43:02  来源:igfitidea点击:

C# Method Caller

c#.net

提问by pistacchio

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

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

Hi, how can i determine the caller of a method from within the method? Eg:

嗨,我如何从方法中确定方法的调用者?例如:

SomeNamespace.SomeClass.SomeMethod() {
   OtherClass();
}

OtherClass() {
   // Here I would like to able to know that the caller is SomeNamespace.SomeClass.SomeMethod
}

Thanks

谢谢

采纳答案by Bogdan Maxim

These articles should be of help:

这些文章应该有帮助:

  1. http://iridescence.no/post/GettingtheCurrentStackTrace.aspx
  2. http://blogs.msdn.com/jmstall/archive/2005/03/20/399287.aspx
  1. http://iridescence.no/post/GettingtheCurrentStackTrace.aspx
  2. http://blogs.msdn.com/jmstall/archive/2005/03/20/399287.aspx

Basically the code looks like this:

基本上代码如下所示:

StackFrame frame = new StackFrame(1);
MethodBase method = frame.GetMethod();
message = String.Format("{0}.{1} : {2}",
method.DeclaringType.FullName, method.Name, message);
Console.WriteLine(message);

回答by Shay Erlichmen

You need to use the StackTraceclass

您需要使用StackTrace

Snippet from the MSDN

摘自 MSDN

// skip the current frame, load source information if available 
StackTrace st = new StackTrace(new StackFrame(1, true)) 
Console.WriteLine(" Stack trace built with next level frame: {0}",
  st.ToString());

回答by M4N

You can use the System.Diagnostics.StackTraceclass:

您可以使用System.Diagnostics.StackTrace类:

  StackTrace stackTrace = new StackTrace();           // get call stack
  StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

  // write call stack method names
  foreach (StackFrame stackFrame in stackFrames)
  {
    Console.WriteLine(stackFrame.GetMethod().Name);   // write method name
  }