zl程序教程

您现在的位置是:首页 >  后端

当前栏目

在.NET中怎样取得代码行数

Net代码 怎样 取得
2023-09-11 14:14:10 时间

文章目的

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

代码

[STAThread]
static void Main(string[] args)
{
     ReportError("Yay!");
}

static private void ReportError(string Message)
{
     StackFrame CallStack = new StackFrame(1, true);
     Console.Write("Error: " + Message + ", File: " + CallStack.GetFileName() + ", Line: " + CallStack.GetFileLineNumber());
}

StackFrame(Int32, Boolean) 初始化与当前堆栈帧之上的帧相应的 StackFrame 类的新实例,能够选择捕获源信息。

GetFileName  :获取包括所运行代码的文件名称。 该信息通常从可运行文件的调试符号中提取。

 

GetMethod  :获取在当中运行帧的方法。

GetFileLineNumber  :获取文件里包括所运行代码的行号。 该信息通常从可运行文件的调试符号中提取。


利用Exception(例外)的StackTrace类

try
{
    throw new Exception();
}
catch (Exception ex)
{
    // Get stack trace for the exception with source file information
    var st = new StackTrace(ex, true);
    // Get the top stack frame
    var frame = st.GetFrame(0);
    // Get the line number from the stack frame
    var line = frame.GetFileLineNumber();
}

.NET4.5 新方法

static void SomeMethodSomewhere()
{
    ShowMessage("Boo");
}
...
static void ShowMessage(string message,
    [CallerLineNumber] int lineNumber = 0,
    [CallerMemberName] string caller = null)
{
     MessageBox.Show(message + " at line " + lineNumber + " (" + caller + ")");
}