从.NET堆栈帧获得的参数值? [英] Obtain parameter values from a stack frame in .NET?

查看:105
本文介绍了从.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?

在code到目前为止是这样的:

The code so far looks like 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.

推荐答案

您不能StackFrames做到这一点。

You can't do this with StackFrames.

一种可能是使用拦截的框架,或者你写你自己的 .NET 的代理。我做了一次,在的 HTTP文件吧:// tdanecker。 blogspot.com/2007/09/interception-with-proxies.html 的。

One possibility would be to use an interception framework, or you write your own with .NET's proxies. I did it once and documented it in http://tdanecker.blogspot.com/2007/09/interception-with-proxies.html.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆