在.NET中取得代码行数的方法
介绍在.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+")");
}