中的堆栈帧获取参数值

中的堆栈帧获取参数值

本文介绍了从 .NET 中的堆栈帧获取参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

I would like to be able to obtain all the parameter values from the stack frame in .NET. A bit like how you're able to see the values in the call stack when in the Visual Studio debugger. My approach has concentrated on using the StackFrame class and then to reflect over a ParameterInfo array. I've had success with reflection and properties, but this is proving a bit trickier.

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

Is there an approach for achieving this?

目前的代码是这样的:

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


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


Just for a bit of context, my plan was to try and use this when I throw my own exceptions. I'll look at your suggestions in more detail and see if I can see it fitting.

推荐答案

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

It seems it can't be done that way. It will only provide meta information about the method and its parameters. Not the actual value at the time of the callstack.

有些人建议从 ContextBoundObject 派生您的类并使用 IMessageSink 所有方法调用都会收到通知以及参数的值.这通常用于 .NET Remoting.

Some suggest deriving your classes from ContextBoundObject and use IMessageSink to be notified off all method calls and the values of the parameters. This is normally used for .NET Remoting.

另一个建议可能是编写一个调试器.这就是 IDE 获取其信息的方式.Microsoft 有 Mdbg,您可以从中获取源代码.或者编写一个 CLR 分析器.

Another suggestion might be to write a debugger. This is how the IDE gets its information. Microsoft has Mdbg of which you can get the source code. Or write a CLR profiler.

这篇关于从 .NET 中的堆栈帧获取参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:33