在.NET中取得代碼行數(shù)的方法
更新時(shí)間:2014年06月03日 16:34:38 作者:
這篇文章主要介紹了在.NET中如何取得代碼行數(shù),需要的朋友可以參考下
文章目的
介紹在.NET中取得代碼行數(shù)的方法
代碼
[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) 初始化與當(dāng)前堆棧幀之上的幀對應(yīng)的 StackFrame 類的新實(shí)例,可以選擇捕獲源信息。
GetFileName :獲取包含所執(zhí)行代碼的文件名。 該信息通常從可執(zhí)行文件的調(diào)試符號中提取。
GetMethod :獲取在其中執(zhí)行幀的方法。
GetFileLineNumber :獲取文件中包含所執(zhí)行代碼的行號。 該信息通常從可執(zhí)行文件的調(diào)試符號中提取。
利用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 + ")");
}
介紹在.NET中取得代碼行數(shù)的方法
代碼
復(fù)制代碼 代碼如下:
[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) 初始化與當(dāng)前堆棧幀之上的幀對應(yīng)的 StackFrame 類的新實(shí)例,可以選擇捕獲源信息。
GetFileName :獲取包含所執(zhí)行代碼的文件名。 該信息通常從可執(zhí)行文件的調(diào)試符號中提取。
GetMethod :獲取在其中執(zhí)行幀的方法。
GetFileLineNumber :獲取文件中包含所執(zhí)行代碼的行號。 該信息通常從可執(zhí)行文件的調(diào)試符號中提取。
利用Exception(例外)的StackTrace類
復(fù)制代碼 代碼如下:
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 新方法
復(fù)制代碼 代碼如下:
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 + ")");
}
相關(guān)文章
ASP.NET MVC制作404跳轉(zhuǎn)實(shí)例(非302和200)
本篇文章主要介紹了ASP.NET MVC制作404跳轉(zhuǎn)實(shí)例(非302和200) ,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04ASP.NET怎么操作DataTable實(shí)例應(yīng)用
有機(jī)會在博客園的博問頻道上看到一個(gè)問題,《ASP.NET怎么操作DataTable》;需要的朋友可以參考下2012-11-11ASP.NET用DataSet導(dǎo)出到Excel的方法
ASP.NET用DataSet導(dǎo)出到Excel的方法,需要的朋友可以參考一下2013-03-03asp.net配置會話狀態(tài)Session實(shí)現(xiàn)代碼
在Web應(yīng)用程序中,都會有一個(gè)Web.config文件來配置當(dāng)前Web項(xiàng)目。其中包括關(guān)于會話狀態(tài)Session的配置2012-10-10