上一行是堆栈中的下一帧。堆栈的顶部是当前行,下一行是前一个调用者(这是您想要的那个)。一个简单的循环应该获取您需要的信息:
static void Main(string[] args)
{
MethodA();//called from line 26 on my code
Console.ReadLine();
}
private static void MethodA()
{
var stacktrace = new StackTrace(true);//be sure to pass true to obtain line info
for (int i = 0; i < stacktrace.FrameCount; i++)
{
var frame = stacktrace.GetFrame(i);
Console.WriteLine("{0}, {1}, {2}, {3}", frame.GetFileLineNumber(), frame.GetMethod(), frame.GetFileName(), frame.GetFileColumnNumber());
}
}
输出:
35、无效方法A()、c:\Development\General\Samples\WindowsFormsApplication1\Cons oleApplication1\Program.cs, 13
26, 无效的 Main(System.String[]), c:\Development\General\Samples\WindowsFormsAppli cation1\ConsoleApplication1\Program.cs, 13
注意这里调用者在第26行