在.NET中取得代碼行數(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) 初始化與當前堆棧幀之上的幀對應的 StackFrame 類的新實例,可以選擇捕獲源信息。
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ù)的方法
代碼
復制代碼 代碼如下:
[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 :獲取包含所執(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 + ")");
}
相關(guān)文章
探究ASP.NET Core Middleware實現(xiàn)方法
這篇文章主要介紹了探究ASP.NET Core Middleware實現(xiàn)方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02
Asp.net內(nèi)置對象之Request對象(概述及應用)
Request對象主要用于獲取來自客戶端的數(shù)據(jù),如用戶填入表單的數(shù)據(jù)、保存在客戶端的Cookie等,本文將圍繞Request對象,講解其的主要作用:讀取窗體變量、讀取查詢字符串變量、取得Web服務器端的系統(tǒng)信息。取得客戶端瀏覽器信息等等,感興趣的朋友可以了解下2013-02-02
MVC使用Memcache+Cookie解決分布式系統(tǒng)共享登錄狀態(tài)學習筆記6
這篇文章主要介紹了MVC使用Memcache+Cookie解決分布式系統(tǒng)共享登錄狀態(tài)學習筆記,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09

