Purpose
This article describes how to obtain the number of lines of code in. NET.
Code
Copy codeThe Code is as follows:
[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) initializes a new instance of the StackFrame class corresponding to the frame above the current stack frame. You can select capture source information.
GetFileName: get the file name that contains the executed code. This information is usually extracted from the debugging symbol of the executable file.
GetMethod: Get the method for executing frames in it.
GetFileLineNumber: gets the row number of the Code executed in the file. This information is usually extracted from the debugging symbol of the executable file.
Exception (Exception) StackTrace class
Copy codeThe Code is as follows:
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 ();
}
New. NET4.5 Method
Copy codeThe Code is as follows:
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 + ")");
}