我正在执行一个名为MethodA的方法,在该方法中,我想得到MethodA的行号。我可以通过
获得这个号码 var lineNumber = stacktrace.GetFrame(i).GetFileLineNumber()
但是,这只获得将在MethodA之后执行的下一行的行号。当MethodA和下一行代码之间有很大的空间时,这就有问题了。
有没有办法在stacktrace中获取当前行的前一行?
编辑: 这个
在第100行的另一个文件中调用MethodAMethodA();
我想找到第100行
编辑:
在发布模式下会发生此错误,但在调试模式下会很好
编辑:
所以当我在构建选项中取消选中优化代码时,我发现我得到了正确的行号。但是这仅在我在发布模式下调试时有效;当我刚刚在发布模式下运行时,我得到了错误的行号。
答案 0 :(得分:2)
前一行是堆栈中的下一帧。堆栈的顶部是当前行,下一行是前一个调用者(这是你想要的那个)。一个简单的循环应该抓住你需要的信息:
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,Void MethodA(), C:\开发\一般\样本\ WindowsFormsApplication1 \缺点 oleApplication1 \ Program.cs,13
26,Void Main(System.String []), C:\开发\一般\样本\ WindowsFormsAppli cation1 \ ConsoleApplication1 \ Program.cs,13
请注意,来电者在线 26