3

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

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

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

4

1 回答 1

2

怎么样:

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?

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

于 2011-07-11T18:36:45.490 回答