2011-04-28 33 views
3

嗨,我有方法讓調用方法的名字:如何獲得真正的方法名稱而不是.ctor?

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

當我跟蹤我的錯誤和異常我總是得到方法名.ctor 如何避免或至少得到這樣的類名< .ctor >?

回答

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? 

使用字符串比較是有點笨拙,但它的工作原理:)

+0

這是真的老問題,其實我不上工作了,但是當我找點時間我會試試:) – TrN 2011-07-13 08:24:22

相關問題