站内搜索: 请输入搜索关键词
当前页面: 图书首页 > From Java To C# A Developers Guide

From Java To C# A Developers Guide

[ directory ] Previous Section Next Section

24.2 #else and #elif

For more control, you can also use the #else and #elif (else if) directives. The example below should clarify their use. Note that each #if can have zero or more #elif 'blocks', zero or one #else 'block', and must end with a corresponding #endif.

Here is an example demonstrating #else.

 1: #define DEBUG
 2: // #define SHOW_ON_CONSOLE
 3:
 4: using System;
 5: using System.Windows.Forms;
 6:
 7: public class TestClass{
 8:
 9:   public static void Main(){
10: #if DEBUG                  // true
11:
12:   #if SHOW_ON_CONSOLE      // false
13:     Console.WriteLine("in Main");
14:   #else
15:     MessageBox.Show("in Main");
16:   #endif // for line 12
17:
18: #endif // for line 10
19:     Console.WriteLine("running statement");
20:   }
21: }

Output:

c:\expt>test
graphics/24fig01.gif
running statement

I have also made use of nested #if directives in this example. You can indent your preprocessor directives too, but use of more than two levels of nesting makes code difficult to read. [2] Lines which eventually make it into IL codes are shown shaded.

[2] The last thing you want is to waste time debugging your preprocessor directives to get your source to compile.

In this program, the developer wishes to show debugging statements either on the console or in pop-up message boxes. This can be done by selectively commenting off (or removing) line 2. The statement on line 15 shows the string "in Main" in a pop-up message box.

The #if and #elif directives can take in not just one symbol, but multiple symbols separated by the following operators: !, ==, !=, ||, and &&. So the above example can be rewritten like this, so that we don't have nested #ifs:

 1: #define DEBUG
 2: // #define SHOW_ON_CONSOLE
 3:
 4: using System;
 5: using System.Windows.Forms;
 6:
 7: public class TestClass{
 8:
 9:   public static void Main(){
10: #if DEBUG && SHOW_ON_CONSOLE // false
11:    Console.WriteLine("in Main");
12: #elif DEBUG                 // true
13:    MessageBox.Show("in Main");
14: #endif
15:
16:    Console.WriteLine("running statement");
17:   }
18: }

The use of #define, #if, #elif, #else and #endif directives to demarcate source codes for compilation is called 'conditional compilation'.

    [ directory ] Previous Section Next Section