如何在VB.net中的应用程序运行打印行数应用程序、行数、如何在、net

2023-09-04 01:17:03 作者:为你戎马今生

我想打印出我的调试消息,在VB.net应用程序的行号。 我不喜欢这样,

I would like to print out my debug message with line number in VB.net application. I did like this,

Dim st As StackTrace
Dim sf As StackFramee
st = New StackTrace(New StackFrame(True))
sf = st.GetFrame(0)
Console.WriteLine.("Line " & sf.GetFileLineNumber())

我想把片段的一类,每次我打电话logMsg方法来记录我的消息,行号源$ C ​​$ C。 但我发现,如果我把上面的代码段为一类,行数总是相同的,这是我新的'圣'。行

I wanna put the snippet to a class, everytime I call logMsg method to log my message with line number in source code. But I found if I put the snippet above into a class, the line number was always same, that's the line which I new 'st'.

的功能是完全一样的具有_ 行的宏C ++。其实我是C ++程序员。

The function is exact same with _LINE macro in C++. Actually I am C++ programmer.

反正来解决这个问题?谢谢。

Anyway to fix this problem? thanks.

推荐答案

您已经证明是工作完全按预期的code。它打印在您拍摄的堆栈帧行的数目。因为你已经在不同的类中定义它,它打印包含类文件的行号。

The code you've shown is working exactly as expected. It's printing the number of the line where you captured the stack frame. Because you've defined it in a different class, it's printing the line number of the file that contains that class.

的getFrame 方法,在这里是非常重要的。栈帧起始编号是0,这是的最后的堆栈帧推。因此,参考帧0,则指示打印的最后的堆栈被推帧的行数的运行时间。当一个方法调用另一个,一个新的堆栈帧创建。

The GetFrame method is important here. Stack frames are numbered starting at 0, which is the last stack frame pushed. So, by referring to frame 0, you are instructing the runtime to print the line number of the last stack frame that was pushed. When one method calls another, a new stack frame is created.

相反,你需要改变你的方法在几个重要方面。首先,你需要获得的第一个的框架被压入堆栈。第二,你可能要接受有关您回应异常含参数的信息。尝试重写你的调试方法看起来是这样的:

Instead, you need to change your method in a couple of important ways. First, you need to get the first frame that was pushed onto the stack. And second, you probably want to accept a parameter containing information about the exception that you are responding to. Try rewriting your debug method to look something like this:

Public Sub PrintCurrentLine(ByVal ex As Exception)
    Dim st As StackTrace = New StackTrace(ex)
    Dim sf As StackFrame = st.GetFrame(st.FrameCount - 1)
    Console.WriteLine("Line " & sf.GetFileLineNumber())
End Sub

还要记住,如果你正在运行的code与优化启用,像行号可能已经改变。你总是需要包括PDB文件与您的code,它包含调试用于在这样的情况的信息。它映射优化code回到原来的来源。

Also remember that if you're running the code with optimizations enabled, things like line numbers may have changed. You always need to include the PDB file with your code, which contains debugging information that is used in situations like this. It maps the optimized code back to your original source.