Conditional compilation is something that C # is more than Java, and conditional compilation is not used in actual project development. But in a recent study of the project found this kind of problem, conditional compilation is C # More than Java out of things, but I consulted with predecessors, They all say conditional compilation is not used in actual project development. Given the new content, I'll take notes and understand.
conditional compilation belongs to the category of compilation preprocessing, which allows us to include or exclude some of the code through the mechanism of conditional compilation, which is similar to If-else.
The conditional compilation directive has the following four types
#if #elif #else #endif
Let's take a few examples to illustrate their usage.
#define Debug
Class Class1
{
#if Debug
void Trace (String s) {}
#endif
}
Because the first line has defined the symbol debug using the # define directive, the #if condition is met, so this code is equivalent to
The code is as follows:
Class Class1
{
void Trace (String s) {}
}
Another example:
The code is as follows:
#define A
#define B
#undef C
Class D
{
#if C
void F () {}
#elif A && B
void I () {}
#else
void G () {}
#endif
}
Its compilation effect is equivalent to:
Copy CodeThe code is as follows:
Class C
{
void I () {}
}
#if directives can be used in nesting, for example:
The code is as follows:
#define DEBUG//debugging on
#undef Trace//tracing off
Class Purchasetransaction
{
void Commit ()
{
#if Debug
CheckConsistency ();
#if Trace
WriteToLog (this. ToString ());
#endif
#endif
Commithelper ();
}
}
Precompilation and conditional compilation directives can also help us to issue compiled errors or warnings during program execution, and the corresponding instructions are #warning and #error, and the following programs show their usage: The code is as follows:
#define DEBUG
#define RELEASE
#define DEMO VERSION
#if DEMO VERSION &&! DEBUG
#warning You is building a demo version
#endif
#if DEBUG && DEMO VERSION
#error You cannot build a debug demo version
#endif
Using System;
Class Demo
{
public static void Main ()
{
Console.WriteLine ("Demo Application");
}
}
C # conditional compilation