Conditional compilation in C.NET study note 5 C

  • 2020-05-07 20:18:43
  • OfStack

Conditional compilation is more of C# than Java, but when I consulted my predecessors, they all said that conditional compilation is not used much in actual project development.
Conditional compilation belongs to the category of compilation preprocessing. It allows us to include or exclude parts of the code through the conditional compilation mechanism, which is similar to if-else.
Conditional compilation instruction has the following 4 kinds 􀁺 # if & # 1048698; # elif & # 1048698; # else & # 1048698; There are four types of conditional compilation instructions
# if
# elif
    # else
# endif
Here are some examples to illustrate their use

#define Debug
  class Class1
 {
      #if Debug
      void Trace(string s) {}
      #endif
 }

Since the symbol Debug has been defined in line 1 using the #define directive, the #if condition is satisfied, this code is equivalent to

class Class1
{
   void Trace(string s) {}
}

Such as:

#define A
   #define B
   #undef C
   class D
  {
      #if C
         void F() {}
             #elif A && B
                void I() {}
      #else
         void G() {}
      #endif
  }

The compilation effect is equivalent to:

class C
{
   void I() {}
}

The #if directive can be nested, for example:

#define Debug // Debugging on 
   #undef Trace // Tracing off
   class PurchaseTransaction
  {
      void Commit() 
    {
      #if Debug
          CheckConsistency();
          #if Trace
            WriteToLog(this.ToString());
          #endif
      #endif
      CommitHelper();
     }
  }

Precompilation and conditional compilation instructions can also help us issue compilation errors or warnings during program execution. The corresponding instructions are #warning and #error. The following program shows their usage:

#define DEBUG 
   #define RELEASE
   #define DEMO VERSION
     #if DEMO VERSION && !DEBUG
        #warning you are building a demo version
     #endif
     #if DEBUG && DEMO VERSION
       #error you cannot build a debug demo version
     #endif
   using System;
   class Demo
  {
     public static void Main()
    {
      Console.WriteLine( " Demo application " );
    }
  }

Author: notifier

Related articles: