首页 > 学院 > 开发设计 > 正文

获取代码所在的位置信息

2019-11-17 03:05:39
字体:
来源:转载
供稿:网友

获取代码所在的位置信息

要实现获取代码所在的位置信息的功能,类System.Diagnostics.StackFrame是关键,源码如下:

1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Diagnostics; //需要知道源码位置
6
7namespace Consoleapplication1
8{
9 class PRogram
10 {
11 static void FirstLevel()
12 {
13 StackFrame stackFrame = new StackFrame(1, true);
14 Console.WriteLine(stackFrame.GetFileName()); //获取包含所执行代码的文件名。
15 Console.WriteLine(stackFrame.GetFileLineNumber().ToString()); //也就是FirstLevel()被调用地方的行号
16 Console.WriteLine(stackFrame.GetFileColumnNumber().ToString()); //也就是FirstLevel()被调用地方的第一个字母“F”所处的列
17 Console.WriteLine(stackFrame.GetMethod().Module); //stackFrame.GetMethod()获取在其中执行帧的方法。
18 Console.WriteLine(stackFrame.GetMethod().ReflectedType);
19 Console.WriteLine(stackFrame.GetMethod().ToString());
20 }
21
22 static void SecondLevel()
23 {
24 FirstLevel();
25 }
26
27 static void Main(string[] args)
28 {
29 SecondLevel();
30 Console.ReadKey();
31 }
32 }
33}

执行结果如下:

C:/Users/Administrator/Desktop/ConsoleApplication1/ConsoleApplication1/Program.cs2413ConsoleApplication1.exeConsoleApplication1.ProgramVoid SecondLevel()

分析如下:

构造函数StackFrame(int skipFrames, bool fNeedFileInfo)中,skipFrames为堆栈上帧跳过当前帧的帧数,fNeedFileInfo表示是否想获取堆栈帧所在文件名、行号、列号(Visual Studio 2010中,定位到构造函数StackFrame(1, true)调用处,按F12,即可看到此信息)。

那么什么是堆栈帧?“堆栈帧是在堆栈中为当前正在运行的函数分配的区域(或空间)。传入的参数、返回地址(当这个函数结束后必须跳转到该返回地址。译注:即主调函数的断点处)以及函数所用的内部存储单元(即函数存储在堆栈上的局部变量)都在堆栈帧中。”(http://book.51cto.com/art/200804/70915.htm)举个例子,A()调用B(),B()调用C(),那么,B()所处的堆栈帧刚好在C()所处堆栈帧的上一个,也就是说B()相对C()的帧跳数为1,A()的相对C()的帧跳数就为2。

好了,明白了这个,再来看将FirstLevel()中“StackFrame stackFrame = new StackFrame(1, true);”改为“StackFrame stackFrame = new StackFrame(2, true);”后的结果:

C:/Users/Administrator/Desktop/ConsoleApplication1/ConsoleApplication1/Program.cs2913ConsoleApplication1.exeConsoleApplication1.ProgramVoid Main(System.String[])


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表