Csharp/CSharp Tutorial/Preprocessing Directives/define

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

A list of preprocessor commands available in C#:

<source lang="csharp">#define

  1. undef
  2. if
  3. else
  4. elif
  5. endif
  6. line
  7. error
  8. warning
  9. region
  1. pragma</source>

Preprocessing Directives: define

  1. The #define directive defines a character sequence called a symbol.
  2. The existence or nonexistence of a symbol can be determined by #if or #elif

The general form for #define:


<source lang="csharp">#define symbol</source>

Use a symbol expression.

<source lang="csharp">#define AAA

  1. define BBB

using System;

class MainClass {

 public static void Main() { 
    
   #if AAA 
     Console.WriteLine("Compiled for AAA version."); 
   #endif 

   #if AAA && BBB 
      Console.Error.WriteLine("Testing AAA and BBB version."); 
   #endif 
  
   Console.WriteLine("This is in all versions."); 
 } 

}</source>

Compiled for AAA version.
Testing AAA and BBB version.
This is in all versions.

Use the Conditional attribute with define

<source lang="csharp">#define USE_METHOD_1 using System; using System.Diagnostics; class MainClass {

 [Conditional("USE_METHOD_1")]
 public static void Method1()
 {
   Console.WriteLine("In Method 1");
 }
 public static void Main() 
 {
     Console.WriteLine("In Main");
   Method1();
 }

}</source>

In Main
In Method 1