C# preprocessor directives
C# includes a number of commands that are known as preprocessor directives. These commands never actually get translated to any commands in your executable code, but instead they affect aspects of the compilation process.
We could use preprocessor directives to prevent the compiler from compiling code related to the additional features when we are compiling the basic version of the software. Another scenario is that we might have written bits of code that are intended to provide we with debugging information.
The preprocessor directives are all distinguished by beginning with the # symbol.
#define is used like this: #define DEBUG
It is a little bit like declaring a variable, except that this variable doesn’t really have a value — it just exists. And this symbol isn’t part of our actual code; it exists only for the benefit of the compiler, while the compiler is compiling the code, and has no meaning within the C# code itself.
#undef does the opposite, and removes the definition of a symbol:
#undef DEBUG
If the symbol doesn’t exist in the first place, then #undef has no effect. Similarly, #define has no effect if a symbol already exists.
#if, #elif, #else, and #endif. These directives inform the compiler whether to compile a block of code. Consider this method:
int DoSomeWork(double x){
// do something
#if DEBUG
Console.WriteLine("x is " + x);
#endif
}
This code will compile as normal, except for the Console.WriteLine() method call that is contained inside the #if clause. This line will be executed only if the symbol DEBUG has been defined by a previous #define directive. When the compiler finds the #if directive, it checks to see if the symbol concerned exists
and compiles the code inside the #if clause only if the symbol does exist. Otherwise, the compiler simply ignores all the code until it reaches the matching #endif directive. Typical practice is to define the symbol DEBUG while we are debugging and have various bits of debugging - related code inside #if clauses. Then, when we are close to shipping, you simply comment out the #define directive, and all the debugging code miraculously disappears, the size of the executable fi le gets smaller, and your end users don ’ t get confused by being shown debugging information.
The #elif (=else if) and #else directives can be used in #if blocks and have intuitively obvious meanings.
A symbol is considered to be true if it exists and false if it doesn’t.
Two other very useful preprocessor directives are #warning and #error. These will respectively cause a warning or an error to be raised when the compiler encounters them.
Дата добавления: 2015-09-18 | Просмотры: 639 | Нарушение авторских прав
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
|