C # has a number of commands called preprocessor directives. These commands are never translated into commands in executable code, but affect all aspects of the compilation process. For example, a preprocessor can prevent a compiler from compiling a portion of the code. You can use these instructions if you plan to release two versions of code, such as the base and enterprise versions, or encode for different versions of the. NET Framework. We can often see this usage in anthem.net code.
The preprocessor directive starts with a symbol #.
Attention:
C # does not have a single preprocessor like C + +, and the so-called preprocessor directives are still handled by the compiler.
The instructions are described below.
1. #define和 #undef
#define可以定义符号. This expression evaluates to True when the symbol is used as an expression passed to the #if instruction. Such as
#define DEBUG
It tells the compiler that there is a symbol for the given name, in this case Debug. This symbol is not part of the actual code, but exists only when the code is compiled.
#undef正好相反, it deletes a symbol.
The #define and #undef commands must be placed at the beginning of the C # source, before any code to be compiled. It does not define constant values as in C + +.
#define本身并无大用, it needs to be used with #if instructions.
Such as
#define DEBUG
int DoSw(double x)
{
#if DEBUG
COnsole.WriteLine("x is"+X);
#edif
}
2. #if, #elif, #else和 #endif
These instructions tell the compiler whether to compile a block of code. Look at the following method:
static void PrintVersion()
{
#if V3
Console.WriteLine("Version 3.0");
#elif V2
Console.WriteLine("Version 2.0");
#else
Console.WriteLine("Version 1.0");
#endif
}
The above code prints different version information based on the defined symbols. This way becomes conditional compilation.
Attention:
Using #if is not the only way to conditionally compile code, C # also provides a mechanism for passing conditional properties.
#if和 #elif also supports a set of logical operators!=,==,!= and | | 。 If the symbol exists, the value of the symbol is considered true, or false, such as:
#if V3 | | (V2 = = true)//if the V3 or V2 symbol is defined ...