gpt4 book ai didi

c# - 从 .NET 中的堆栈帧获取参数值?

转载 作者:可可西里 更新时间:2023-11-01 03:02:02 25 4
gpt4 key购买 nike

我希望能够从 .NET 中的堆栈帧中获取所有参数值。有点像您在 Visual Studio 调试器中查看调用堆栈中的值的方式。我的方法集中在使用 StackFrame class然后反射(reflection)过来一个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

仅供引用,我的计划是在抛出自己的异常时尝试使用它。我会更详细地查看您的建议,看看是否合适。

最佳答案

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

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

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

关于c# - 从 .NET 中的堆栈帧获取参数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com