我们在学习函数调用时,都知道每个函数都拥有自己的栈空间。一个函数被调用时,就创建一个新的栈空间。那么通过函数的嵌套调用最后就形成了一个函数调用堆栈。在c#中,使用StackTrace记录这个堆栈。你可以在程序运行过程中使用StackTrace得到当前堆栈的信息。
class Program { static void Main(string[] args) { Program a = new Program(); a.FuncA(); Console.ReadLine(); } int FuncA() { FuncB(); return 0; } private void FuncB() { MethodInfo method0 = (MethodInfo)(new StackTrace().GetFrame(0).GetMethod()); MethodInfo method1 = (MethodInfo)(new StackTrace().GetFrame(1).GetMethod()); MethodInfo method2 = (MethodInfo)(new StackTrace().GetFrame(2).GetMethod()); Console.WriteLine("Current Method is : {0}",method0.Name); Console.WriteLine("Parent Method is : {0}", method1.Name); Console.WriteLine("GrandParent Method is : {0}", method2.Name); } }