When we learn function calls, we all know that each function has its own stack space. When a function is called, a new stack space is created. Then a function call stack is finally formed through nested calls to functions. In C #, use StackTrace to record this stack. You can use StackTrace to get information about the current stack while the program is running.
classProgram {Static voidMain (string[] args) {Program A=NewProgram (); A.funca (); Console.ReadLine (); } intFunca () {FUNCB (); return 0; } Private voidFUNCB () {MethodInfo method0= (MethodInfo) (NewStackTrace (). GetFrame (0). GetMethod ()); MethodInfo method1= (MethodInfo) (NewStackTrace (). GetFrame (1). GetMethod ()); MethodInfo method2= (MethodInfo) (NewStackTrace (). 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); } }
The output of the program is:
Current Method IS:FUNCB
Parent Method Is:funca
Grandparent Method Is:main
Where call GetFrame to get the stack space, the parameter index represents the level of stack space, 0 represents the current stack space, 1 represents the upper level of stack space, and so on.
In addition to obtaining method information, you can also call the member function of the StackFrame class to get the file information, line number, and column number of the code at run time. For details, refer to a example on MSDN.
//Display the Stack frame properties.StackFrame SF =St. GetFrame (i); Console.WriteLine ("File: {0}", SF. GetFileName ()); Console.WriteLine ("Line number : {0}", SF. Getfilelinenumber ());//Note that the column number defaults to zero//When is not initialized.Console.WriteLine ("Column number: {0}", SF. Getfilecolumnnumber ());if(SF. Getiloffset ()! =Stackframe.offset_unknown) {Console.WriteLine ("Intermediate Language Offset: {0}", SF. Getiloffset ());}if(SF. Getnativeoffset ()! =Stackframe.offset_unknown) {Console.WriteLine ("Native Offset: {0}", SF. Getnativeoffset ());}
In Dudu's article attribute application in. NET programming (iv) in the article, it is through StackTrace to obtain its upper level of function information, that is, addcustomer information, to further create SqlParameter. See its article for details.
Brief analysis of StackTrace