The conditional compilation directive has the following four types:
#if
#elfi
#else
#endif
These conditional compilation directives are used to conditionally include or exclude part of a program segment. They have a similar effect to the IF statement in C #. You can use the logical operator with (&&) in the instruction, or (| |) and take the inverse operator (!) Wait The order in which they appear in the program must be this:
A #if statement (must have)
0 or more #elif statements
0 or a #else statement
A #endif statement (must have)
Here are some examples to illustrate their use.
#define Debug
Class Class1
{
#if Debug
void Trace (String s) {}
}
Another example:
#define A
#define B
#undef C
class D
{
#if c
void F () {}
#elif A && b
void I () {}< c9/> #else
void G () {}
#endif
}
It is not difficult to see that the actual compilation of the effect is equivalent to:
Class C
{
void I () {}
}
In this example, please note the use of the #elif directive, which means: "Else if", using #elif can add one or more branches to the #if instruction.
#if指令可以嵌套使用, for example:
#define DEBUG //debugging on
#undef Trace //tracing off
class Purchase Transaction
{
void Commit () {
#if Debug
checkconsistency ();
#if Trace
WriteToLog (this. ToString ());
#endif
#enfif
commithelper ();
}
Preprocessing directives are not executed if they appear in the middle of other output-output elements. For example, the following program tries to show Hello World when debug is defined, otherwise the hello everyone is displayed, but the result is a laugh and cry:
Program Listing 8-6:
Using System;
Class Hello
{
static void Main () {
System.Console.WriteLine (@ "Hello,
#if Debug
World #else
everyone
#endif
");
}
The output of the program is as follows:
Hello,
#if Debug World
#else
everyone
#endif