在.NET中取得代码行数的方法

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了在.NET中取得代码行数的方法脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
文章目的

介绍在.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中取得代码行数的方法全部内容,希望文章能够帮你解决在.NET中取得代码行数的方法所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: