在.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 + ")");
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值