在.NET中取得代码行数的方法
更新时间:2021年9月22日 10:12 点击:1591
文章目的
介绍在.NET中取得代码行数的方法
代码
[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 :获取包含所执行代码的文件名。 该信息通常从可执行文件的调试符号中提取。
GetMethod :获取在其中执行帧的方法。
GetFileLineNumber :获取文件中包含所执行代码的行号。 该信息通常从可执行文件的调试符号中提取。
利用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中取得代码行数的方法
代码
复制代码 代码如下:
[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 :获取包含所执行代码的文件名。 该信息通常从可执行文件的调试符号中提取。
GetMethod :获取在其中执行帧的方法。
GetFileLineNumber :获取文件中包含所执行代码的行号。 该信息通常从可执行文件的调试符号中提取。
利用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 + ")");
}
相关文章
- 这篇文章给大家讲解了下作为程序员如何统计自己写过的代码的行数,这个也是证明自己程序员能力的一个表现,一起来看下。...2020-06-25
C语言实现的统计php代码行数功能源码(支持文件夹、多目录)
这篇文章主要介绍了C语言实现的统计php代码行数功能源码,支持文件夹、多级目录的统计,在一些环境中会用到这个功能,需要的朋友可以参考下...2020-04-25- 今天小编就为大家分享一篇关于C++小知识:不要节约代码行数,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧...2020-04-25
- 这篇文章主要介绍了在.NET中如何取得代码行数,需要的朋友可以参考下...2021-09-22
- 这篇文章主要介绍了idea统计代码行数Statistic的步骤详解,本文通过使用Statistic插件操作的,通过图文实例相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-26