Overview
#if/#endif statements are commonly used to generate different compilation results based on the same source code, the most common of which is the debug and release versions. However, these tools are not very friendly in practical applications because they are easily abused and their code pages are difficult to understand or debug. This problem is considered in the C # design and provides a better tool--conditional feature to compile different machine codes for different environments. The conditional attribute is applied to the level of the method, which forces us to split the conditional code into separate methods. When you need to write conditional code, we should use the conditional attribute instead of the #if/#endif.
function Description
Disadvantages of using #if/#endif statements
For example, write a private method to get the name of the function that called it:
private string Checkmethod () { #if debug Tra Ce. WriteLine ( entering CheckState for Person ); string methodName = new StackTrace (). GetFrame (1 ). GetMethod (). Name; return MethodName; #endif return null
Better solution-Use the conditional feature
To avoid the above problem we can use the conditional feature. Using the conditional attribute, you can split some functions so that they can be compiled and become part of the class only after you have defined certain environment variables or set a value. The most common place to conditional features is to say a piece of code into a debug statement. Isolation strategies using the conditional feature are #endif不容易出错 than #if/.
Look at the following code:
[Conditional ("DEBUG")] Private void Checkmethod () { Trace.WriteLine ("Entering checkstatefor Person"); string New StackTrace (). GetFrame (1). GetMethod (). Name; }
Limitations of conditional characteristics
The conditional feature can only be applied to the entire method.
Any method that uses the conditional attribute can only return a void type.
Feature Extensions
We can configure the solution file to determine the code to run at compile time, the process is as follows:
1. Configure Solution Information:
2. Write code constraints:
[Conditional ("in_memory")] Private Static void configureinmemory () { ................................................ } [Conditional ("NHIBERNATE")] Privatestaticvoid configureinmemory () {
................................................
}
Code generation, we can according to conditional to determine the process of compiling the walk;
C # uses the conditional attribute instead of the # if conditional compilation