在下面的示例中,我在每个方法中插入调试信息,以便我可以 看看调用了哪个函数:
namespace A
{
class A1
{
void f1()
{
Console.WriteLine("inside A.A1.f1"); //1
}
void f2()
{
Console.WriteLine("inside A.A1.f2"); //2
}
}
}
在不同的命名空间和类下有数百种方法
在每种方法中逐个插入调试消息是麻烦的,浪费时间
而不是像上面插入方法特定的调试消息
有更好的方法吗?
也许一个API函数可以告诉我哪个方法?
答案 0 :(得分:1)
StackTrace和StackFrame类可能会提供您需要的信息(请注意,内联方法不会获得堆栈帧):
catch (Exception e)
{
StackTrace st = new StackTrace();
StackTrace st1 = new StackTrace(new StackFrame(true));
Console.WriteLine(" Stack trace for Main: {0}",
st1.ToString());
Console.WriteLine(st.ToString());
}
答案 1 :(得分:1)
如果您使用的是VS 2012,我会告诉您在WriteLine
中使用 Caller Information 。
不幸的是在VS2010中这是不可能的。你可以打电话给这样的东西,但它真的不具备高性能:
namespace A
{
public static class DebugHelper
{
[Conditional("DEBUG")]
public static void LogMethodName()
{
var method = new StackFrame(1).GetMethod();
Console.WriteLine("inside {0}.{1}", method.DeclaringType, method.Name);
}
}
class A1
{
void f1()
{
DebugHelper.LogMethodName(); //1
}
void f2()
{
DebugHelper.LogMethodName(); //2
}
}
}