我希望能够从.NET的堆栈框架中获得所有参数值,就像在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
为了提供一点背景,我的计划是在抛出自己的异常时尝试使用它。我会更详细地研究你的建议,看看是否合适。
https://stackoverflow.com/questions/75076
复制相似问题