gpt4 book ai didi

stack-trace - 如何获取真正的方法名称而不是 .ctor?

转载 作者:行者123 更新时间:2023-12-02 02:26:20 25 4
gpt4 key购买 nike

嗨,我有方法获取调用方法的名称:

    public static string GetMethodName()
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();
return trace.GetFrame(1).GetMethod().Name;
}

当我跟踪错误和异常时,我总是得到方法名称 .ctor如何避免这种情况或至少得到类似 ClassName<.ctor> 的东西?

最佳答案

怎么样:

StackTrace stackTrace = new StackTrace();
foreach(StackFrame sf in stackTrace.GetFrames())
{
if (!sf.GetMethod().Name.StartsWith(".")) // skip all the ".ctor" methods
{
return sf.GetMethod().DeclaringType.Name + "." + sf.GetMethod().Name;
}
}
return "??"; // What do you want here?

使用字符串比较有点笨拙,但它有效:)

关于stack-trace - 如何获取真正的方法名称而不是 .ctor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5819647/

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