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 {}
}