【问题标题】:C# Method Caller [duplicate]C#方法调用者[重复]
【发布时间】:2010-11-12 21:38:46
【问题描述】:

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

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

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

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

谢谢

【问题讨论】:

标签: c# .net


【解决方案1】:

这些文章应该会有所帮助:

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

代码基本上是这样的:

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

【讨论】:

  • 请小心。我曾经被这个错误抓住过。如果您构建应用程序以进行发布,则该方法可以内联,并且您的堆栈跟踪看起来会有所不同。
【解决方案2】:

你需要使用StackTrace

来自 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());

【讨论】:

    【解决方案3】:

    您可以使用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
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 2011-09-27
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多