当前位置:Gxlcms > asp.net > 在.NET中取得代码行数的方法

在.NET中取得代码行数的方法

时间:2021-07-01 10:21:17 帮助过:38人阅读

文章目的

介绍在.NET中取得代码行数的方法

代码
代码如下:
  1. <br>[STAThread] <br>static void Main(string[] args) <br>{ <br>ReportError("Yay!"); <br>} <br><br>static private void ReportError(string Message) <br>{ <br>StackFrame CallStack = new StackFrame(1, true); <br>Console.Write("Error: " + Message + ", File: " + CallStack.GetFileName() + ", Line: " + CallStack.GetFileLineNumber()); <br>} <br> <br>StackFrame(Int32, Boolean) 初始化与当前堆栈帧之上的帧对应的 StackFrame 类的新实例,可以选择捕获源信息。 <br><br>GetFileName :获取包含所执行代码的文件名。 该信息通常从可执行文件的调试符号中提取。 <br><br>GetMethod :获取在其中执行帧的方法。 <br><br>GetFileLineNumber :获取文件中包含所执行代码的行号。 该信息通常从可执行文件的调试符号中提取。 <br><br>利用Exception(例外)的StackTrace类 <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br>try <br>{ <br>throw new Exception(); <br>} <br>catch (Exception ex) <br>{ <br>// Get stack trace for the exception with source file information <br>var st = new StackTrace(ex, true); <br>// Get the top stack frame <br>var frame = st.GetFrame(0); <br>// Get the line number from the stack frame <br>var line = frame.GetFileLineNumber(); <br>} <br> <br>.NET4.5 新方法 <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br>static void SomeMethodSomewhere() <br>{ <br>ShowMessage("Boo"); <br>} <br>... <br>static void ShowMessage(string message, <br>[CallerLineNumber] int lineNumber = 0, <br>[CallerMemberName] string caller = null) <br>{ <br>MessageBox.Show(message + " at line " + lineNumber + " (" + caller + ")"); <br>} <br></li><li> </li><li> </li></ol></pre></li></ol></pre>

人气教程排行