文章目的

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


相关文章:

  • 2021-12-03
  • 2022-12-23
  • 2022-12-23
  • 2021-09-16
  • 2022-02-26
  • 2021-06-07
  • 2021-08-25
猜你喜欢
  • 2022-02-01
  • 2022-02-21
  • 2021-09-14
  • 2022-12-23
  • 2021-11-06
  • 2021-04-10
相关资源
相似解决方案