代码之家  ›  专栏  ›  技术社区  ›  Martin Clarke

从中的堆栈帧获取参数值。网?

  •  21
  • Martin Clarke  · 技术社区  · 16 年前

    我希望能够从中的堆栈帧中获取所有参数值。网。这有点像在Visual Studio调试器中查看调用堆栈中的值。我的方法集中在使用 StackFrame class 然后反思 ParameterInfo 阵列。我在反射和属性方面取得了成功,但事实证明这有点棘手。

    是否有实现这一目标的方法?

    到目前为止,代码看起来像这样:

    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.Go(1);
        }
    }
    
    public class A
    {
        internal void Go(int x)
        {
            B b = new B();
            b.Go(4);
        }
    }
    
    public class B
    {
        internal void Go(int y)
        {
            Console.WriteLine(GetStackTrace());
    
        }
        public static string GetStackTrace()
        {
            StringBuilder sb = new StringBuilder();
            StackTrace st = new StackTrace(true);
            StackFrame[] frames = st.GetFrames();
    
            foreach (StackFrame frame in frames)
            {
                MethodBase method = frame.GetMethod();
    
                sb.AppendFormat("{0} - {1}",method.DeclaringType, method.Name);
                ParameterInfo[] paramaters = method.GetParameters();
                foreach (ParameterInfo paramater in paramaters)
                {
                    sb.AppendFormat("{0}: {1}", paramater.Name, paramater.ToString());
                }
                sb.AppendLine();
            }
            return sb.ToString();
        }
    }
    

    输出如下:

    SfApp.B - GetStackTrace
    SfApp.B - Go
    y: Int32 y
    SfApp.A - Go
    x: Int32 x
    SfApp.Program - Main
    args: System.String[] args
    

    我希望它看起来更像这样:

    SfApp.B - GetStackTrace
    SfApp.B - Go
    y: 4
    SfApp.A - Go
    x: 1
    SfApp.Program - Main
    

    只是为了了解一下上下文,我的计划是在抛出自己的异常时尝试使用它。我会更详细地研究你的建议,看看是否合适。

    2 回复  |  直到 12 年前
        1
  •  8
  •   Peter Mortensen icecrime    12 年前

    看来不能那样做。它只会提供有关方法及其参数的元信息。不是调用堆栈时的实际值。

    有些人建议你的类来自 ContextBoundObject 和使用 IMessageSink 将收到所有方法调用和参数值的通知。这通常用于 .NET Remoting .

    另一个建议可能是编写调试器。这就是IDE获取信息的方式。微软已经 Mdbg 你可以得到它的源代码。或者写一个 CLR profiler .