zoukankan      html  css  js  c++  java
  • 浅析StackTrace

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


    // 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());
    }

    在dudu的文章Attribute在.NET编程中的应用(四)一文中,就是通过StackTrace得到了其上一级的函数信息,即AddCustomer的信息,来进一步创建SqlParameter 的。详情请参见其文章

  • 相关阅读:
    Xib和storyboard对比
    IOS中用模型取代字典的好处
    IOS中UIButton和UIImageView的区别
    Response对象
    ASP.NET内置对象
    ASP.NET最常用的页面生命周期事件
    构造函数与析构函数
    C#程序设计基础——类、对象、方法
    CI框架分页(不解错误)
    Linux 下直连ipad mini充电(实战)
  • 原文地址:https://www.cnblogs.com/mingyongcheng/p/3123293.html
Copyright © 2011-2022 走看看