Книга: C# 2008 Programmer

#if, #else, #elif, and #endif

#if, #else, #elif, and #endif

As you saw in the preceding section, the #if and #endif preprocessor directives defines a block of code to include for compilation if a specified symbol is defined. You can also use the #else and #elif preprocessor directives to create compound conditional directives.

Using the previous example, you can add the #else and #elif preprocessor directives as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestDefine {
 class Program {
  static void Main(string[] args) {
   Console.Write("Please enter a number: ");
   int num = int.Parse(Console.ReadLine());
   int sum = 0;
   for (int i = 1; i <= num; i++) {
    //---sum up all odd numbers---
    if (i % 2 == 1) {
     sum += i;
     Console.WriteLine("i={0}, sum={1}", i, sum);
#elif NORMAL
     Console.WriteLine("sum={0}", sum);
    "Sum of all odd numbers from 1 to {0} is {1}",
     num, sum);

Figure 3-15 shows the different output when different symbols are defined. The top screen shows the output when the DEBUG symbol is defined. The middle screen shows the output when the NORMAL symbol is defined. The bottom screen shows the output when no symbol is defined.

Figure 3-15

The #if preprocessor directive can also test for multiple conditions using the logical operators. Here are some examples:

#if (DEBUG || NORMAL) //---either DEBUG or NORMAL is defined---
#if (DEBUG && NORMAL) //---both DEBUG and NORMAL are defined---
#if (!DEBUG && NORMAL) //---DEBUG is not defined AND NORMAL is defined---

Оглавление книги

Генерация: 1.264. Запросов К БД/Cache: 3 / 1
Вверх Вниз