zl程序教程

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

当前栏目

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

Net方法代码 取得 行数
2023-06-13 09:15:27 时间
文章目的

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

代码
复制代码代码如下:

[STAThread]
staticvoidMain(string[]args)
{
ReportError("Yay!");
}

staticprivatevoidReportError(stringMessage)
{
StackFrameCallStack=newStackFrame(1,true);
Console.Write("Error:"+Message+",File:"+CallStack.GetFileName()+",Line:"+CallStack.GetFileLineNumber());
}

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

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

GetMethod:获取在其中执行帧的方法。

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

利用Exception(例外)的StackTrace类
复制代码代码如下:

try
{
thrownewException();
}
catch(Exceptionex)
{
//Getstacktracefortheexceptionwithsourcefileinformation
varst=newStackTrace(ex,true);
//Getthetopstackframe
varframe=st.GetFrame(0);
//Getthelinenumberfromthestackframe
varline=frame.GetFileLineNumber();
}

.NET4.5新方法
复制代码代码如下:
staticvoidSomeMethodSomewhere()
{
ShowMessage("Boo");
}
...
staticvoidShowMessage(stringmessage,
[CallerLineNumber]intlineNumber=0,
[CallerMemberName]stringcaller=null)
{
MessageBox.Show(message+"atline"+lineNumber+"("+caller+")");
}