在.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+")");
}
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短