C #5.0 CallerMemberName CallerFilePath CallerLineNumber in. NE

Source: Internet
Author: User

C #5.0 brings us three very useful compiler features

CallerMemberName

CallerFilePath

CallerLineNumber

In C and C ++, the following characters help us to debug the message's file line number.

01. # define debug_msg printf ("% s [% d]:" ,__ FILE __,__ LINE _); printf

Which of the following functions is equal to that in. NET 4?

New StackTrace (true ). getFrame (1 ). getMethod (). name ,. in NET4, it is obtained at runtime, and in C #5.0, it should be specified at compilation. For the reason, refer to the following)

In C #5.0, we can use the following code to obtain the line number of the debugging information file:


Public static void TraceMessage (string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Trace. WriteLine ("message:" + message );
Trace. WriteLine ("member name:" + memberName );
Trace. WriteLine ("source file path:" + sourceFilePath );
Trace. WriteLine ("source line number:" + sourceLineNumber );
}
Compile and debug with VS2012 to view the file, row number, and caller method name.

The three features are in. NET 4.5. If they are used in. NET4, define the features:


Namespace System. Runtime. CompilerServices
{
[AttributeUsage (AttributeTargets. Parameter, AllowMultiple = false, Inherited = false)]
Public class CallerMemberNameAttribute: Attribute {}

[AttributeUsage (AttributeTargets. Parameter, AllowMultiple = false, Inherited = false)]
Public class CallerFilePathAttribute: Attribute {}

[AttributeUsage (AttributeTargets. Parameter, AllowMultiple = false, Inherited = false)]
Public class CallerLineNumberAttribute: Attribute {}
}

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.