陋室铭
永远也不要停下学习的脚步(大道至简至易)

posts - 2169,comments - 570,views - 413万
我们在学习函数调用时,都知道每个函数都拥有自己的栈空间。一个函数被调用时,就创建一个新的栈空间。那么通过函数的嵌套调用最后就形成了一个函数调用堆 栈。在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);
         }

     }

程序的输出结果是:
Current Method is : FuncB
Parent Method is : FuncA
GrandParent Method is : Main

       其中调用GetFrame得到栈空间,参数index 表示栈空间的级别,0表示当前栈空间,1表示上一级的栈空间,依次类推。
        除了可以获取方法信息外,还可以调用StackFrame类的成员函数,在运行时得到代码的文件信息及行号和列号等。详情可以参考msdn上的一个example

msdn example
// 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 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());
}
posted on   宏宇  阅读(344)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
< 2009年5月 >
26 27 28 29 30 1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31 1 2 3 4 5 6

点击右上角即可分享
微信分享提示