如何获得真正的方法名称而不是.ctor?

时间:2011-04-28 13:47:59

标签: stack-trace method-names

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

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

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

1 个答案:

答案 0 :(得分: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?

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