【问题标题】:How to get real method name istead of .ctor?如何获取真实的方法名称而不是 .ctor?
【发布时间】:2011-08-14 17:56:48
【问题描述】:

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

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

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

【问题讨论】:

    标签: stack-trace method-names


    【解决方案1】:

    怎么样:

    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?
    

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

    【讨论】:

    • 这是一个非常老的问题,我实际上已经不再研究它了,但是当我找到一些时间时,我会尝试它:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 2014-12-01
    • 1970-01-01
    相关资源
    最近更新 更多