How to get the number of lines of code in. NET

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.