找出哪个类调用了一个方法

时间:2009-06-11 23:35:38

标签: c# .net class

在C#中,有没有办法让一个类或方法知道谁(即什么类/方法)调用它?

例如,我可能有

class a{
   public void test(){
         b temp = new b();
         string output = temp.run();
   }
}

class b{
   public string run(){
        **CODE HERE**
   }
}

输出: “由'a'类的'测试'方法调用。”

5 个答案:

答案 0 :(得分:13)

的StackFrame

var frame = new StackFrame(1);

Console.WriteLine("Called by method '{0}' of class '{1}'",
    frame.GetMethod(),
    frame.GetMethod().DeclaringType.Name);

答案 1 :(得分:2)

您可以查看堆栈跟踪以确定谁调用它。

http://msdn.microsoft.com/en-us/library/system.environment.stacktrace.aspx

答案 2 :(得分:1)

您可以创建并检查检查System.Diagnostics.StackTrace

答案 3 :(得分:0)

以下表达式将为您提供调用方法。

StackTrace()GetFrame(1)GetMethod()

答案 4 :(得分:0)

StackFrame会像Jimmy建议的那样去做。但是,请注意使用StackFrame时。实例化它是相当昂贵的,并且根据您实例化它的确切位置,您可能需要指定MethodImplOptions.NoInlining。如果你希望结束堆栈遍历来找到一个完全函数的被调用者的调用者,你需要这样做:

[MethodImpl(MethodImplOptions.NoInlining)]
public static MethodBase GetThisCaller()
{
    StackFrame frame = StackFrame(2); // Get caller of the method you want
                                      // the caller for, not the immediate caller
    MethodBase method = frame.GetMethod();
    return method;
}
相关问题