Direktivy C # preprocesoru

V tomto kurzu se dozvíme o direktivách preprocesoru, dostupných direktivách v C # a kdy, proč a jak se používají.

Jak název ospravedlňuje, direktivy preprocesoru jsou blok příkazů, které se zpracovávají před spuštěním skutečné kompilace. Direktivy preprocesoru C # jsou příkazy pro kompilátor, který ovlivňuje proces kompilace.

Tyto příkazy určují, které části kódu se mají kompilovat nebo jak zpracovat konkrétní chyby a varování.

Direktiva preprocesoru C # začíná # (hash)symbolem a všechny direktivy preprocesoru trvají na jednom řádku. Direktivy preprocesoru jsou ukončeny new linespíše než semicolon.

Direktivy preprocesoru dostupné v C # jsou:

Direktivy preprocesoru v C #
Směrnice o předzpracovateli Popis Syntax
#if Zkontroluje, zda je výraz preprocesoru pravdivý nebo ne
 #if preprocesorový výrazový kód pro kompilaci #endif
#elif Používá se spolu s #ifke kontrole více výrazů preprocesoru
 #if preprocesor-výraz-1 kód pro kompilaci #elif preprocesor-výraz-2 kód pro kompilaci #endif
#else Používá se spolu s #ifk vytvoření složené podmíněné směrnice.
 #if preprocesorový výrazový kód pro kompilaci #elif kód pro kompilaci #endif
#endif Používá se spolu s #ifk označení konce podmíněné směrnice
 #if preprocesorový výrazový kód pro kompilaci #endif
#define Používá se k definování symbolu
 # definovat SYMBOL
#undef Používá se k nedefinování symbolu
 #undef SYMBOL
#warning Umožňuje nám generovat varování úrovně 1 z našeho kódu
 #warning warning-message
#error Umožňuje nám generovat chyby z našeho kódu
 #error error-message
#line Umožňuje nám upravit číslo řádku a název souboru kompilátoru tak, aby zobrazovaly chyby a varování
 #line line-number název-souboru
#region Umožňuje nám vytvořit oblast, kterou lze rozbalit nebo sbalit při použití editoru kódu Visual Studio
 #regiony s popisem regionu #endregion
#endregion Označuje konec regionu
 #regiony s popisem regionu #endregion
#pragma Poskytuje kompilátoru speciální pokyny pro kompilaci souboru, ve kterém se objeví.
 #pragma pragma-name pragma-argumenty

# definovat směrnici

  • #defineSměrnice nám umožňuje definovat symbol.
  • Symboly, které jsou definovány při použití společně se #ifsměrnicí, se vyhodnotí jako true.
  • Tyto symboly lze použít k určení podmínek pro kompilaci.
  • Syntax:
     # definovat SYMBOL
  • Například:
     #define TESTOVÁNÍ
    TESTOVÁNÍ je zde symbol.

#undef směrnice

  • #undefSměrnice nám umožňuje ZAKAŽ symbol.
  • Nedefinované symboly při použití společně s #ifdirektivou se vyhodnotí jako false.
  • Syntax:
     #undef SYMBOL
  • Například:
     #undef TESTOVÁNÍ
    TESTOVÁNÍ je zde symbol.

#if směrnice

  • #ifSměrnice se používá k testování výrazu preprocesoru.
  • Výraz preprocesoru se může skládat pouze ze symbolu nebo kombinace symbolů spolu s operátory jako &&(AND), ||(OR), !(NOT).
  • #ifpo směrnici následuje #endifsměrnice.
  • Kódy uvnitř #ifsměrnice jsou kompilovány pouze v případě, že výraz testovaný pomocí je #ifvyhodnocen jako true.
  • Syntax:
     #if preprocesorový výrazový kód pro kompilaci <#endif
  • Například:
    #if TESTOVÁNÍ Console.WriteLine ("právě se testuje"); #endif

Příklad 1: Jak používat direktivu #if?

 #define CSHARP using System; namespace Directive ( class ConditionalDirective ( public static void Main(string() args) ( #if (CSHARP) Console.WriteLine("CSHARP is defined"); #endif ) ) ) 

Když spustíme program, výstup bude:

 CSHARP is defined

In the above program, CSHARP symbol is defined using the #define directive at the beginning of program. Inside the Main() method, #if directive is used to test whether CSHARP is true or not. The block of code inside #if directive is compiled only if CSHARP is defined.

#elif directive

  • The #elif directive is used along with #if directive that lets us create a compound conditional directive.
  • It is used when testing multiple preprocessor expression.
  • The codes inside the #elif directive is compiled only if the expression tested with that #elif evaluates to true.
  • Syntax:
     #if preprocessor-expression-1 code to compile #elif preprocessor-expression-2 code-to-compile #endif
  • For example:
     #if TESTING Console.WriteLine("Currently Testing"); #elif TRAINING Console.WriteLine("Currently Training"); #endif

#else directive

  • The #else directive is used along with #if directive.
  • If none of the expression in the preceding #if and #elif (if present) directives are true, the codes inside the #else directive will be compiled.
  • Syntax:
     #if preprocessor-expression-1 code to compile #elif preprocessor-expression-2 code-to-compile #else code-to-compile #endif
  • For example:
     #if TESTING Console.WriteLine("Currently Testing"); #elif TRAINING Console.WriteLine("Currently Training"); #else Console.WriteLine("Neither Testing nor Training"); #endif

#endif directive

  • The #endif directive is used along with #if directive to indicate the end of #if directive.
  • Syntax:
     #if preprocessor-expression-1 code to compile #endif
  • For example:
     #if TESTING Console.WriteLine("Currently Testing"); #endif

Example 2: How to use conditional directive (if, elif, else, endif) ?

 #define CSHARP #undef PYTHON using System; namespace Directive ( class ConditionalDirective ( static void Main(string() args) ( #if (CSHARP && PYTHON) Console.WriteLine("CSHARP and PYTHON are defined"); #elif (CSHARP && !PYTHON) Console.WriteLine("CSHARP is defined, PYTHON is undefined"); #elif (!CSHARP && PYTHON) Console.WriteLine("PYTHON is defined, CSHARP is undefined"); #else Console.WriteLine("CSHARP and PYTHON are undefined"); #endif ) ) )

When we run the program, the output will be:

 CSHARP is defined, PYTHON is undefined

In this example, we can see the use of #elif and #else directive. These directive are used when there are multiple conditions to be tested. Also, symbols can be combined using logical operators to form a preprocessor expression.

#warning directive

  • The #warning directive allows us to generate a user-defined level one warning from our code.
  • Syntax:
     #warning warning-message
  • For example:
     #warning This is a warning message

Example 3: How to use #warning directive?

 using System; namespace Directives ( class WarningDirective ( public static void Main(string() args) ( #if (!CSHARP) #warning CSHARP is undefined #endif Console.WriteLine("#warning directive example"); ) ) ) 

When we run the program, the output will be:

 Program.cs(10,26): warning CS1030: #warning: 'CSHARP is undefined' (/home/myuser/csharp/directives-project/directives-project.csproj) #warning directive example

After running the above program, we will see the output as above. The text represents a warning message. Here, we are generating a user-defined warning message using the #warning directive.

Note that the statements after the #warning directive are also executed. It means that the #warning directive does not terminate the program but just throws a warning.

#error directive

  • The #error directive allows us to generate a user-defined error from our code.
  • Syntax:
     #error error-message
  • For example:
     #error This is an error message

Example 4: How to use #error directive?

 using System; namespace Directive ( class Error ( public static void Main(string() args) ( #if (!CSHARP) #error CSHARP is undefined #endif Console.WriteLine("#error directive example"); ) ) ) 

When we run the program, the output will be:

 Program.cs(10,24): error CS1029: #error: 'CSHARP is undefined' (/home/myuser/csharp/directives-project/directives-project.csproj) The build failed. Please fix the build errors and run again.

We will see some errors, probably like above. Here we are generating a user-defined error.

Another thing to note here is the program will be terminated and the line #error directive example won't be printed as it was in the #warning directive.

#line directive

  • The #line directive allows us to modify the line number and the filename for errors and warnings.
  • Syntax:
     #line line-number file-name
  • For example:
     #line 50 "fakeprogram.cs"

Example 5: How to use #line directive?

 using System; namespace Directive ( class Error ( public static void Main(string() args) ( #line 200 "AnotherProgram.cs" #warning Actual Warning generated by Program.cs on line 10 ) ) ) 

When we run the program, the output will be:

 AnotherProgram.cs(200,22): warning CS1030: #warning: 'Actual Warning generated by Program.cs on line 10' (/home/myuser/csh arp/directive-project/directive-project.csproj)

We have saved the above example as Program.cs. The warning was actually generated at line 10 by Program.cs. Using the #line directive, we have changed the line number to 200 and the filename to AnotherProgram.cs that generated the error.

#region and #endregion directive

  • The #region directive allows us to create a region that can be expanded or collapsed when using a Visual Studio Code Editor.
  • This directive is simply used to organize the code.
  • The #region block can not overlap with a #if block. However, a #region block can be included within a #if block and a #if block can overlap with a #region block.
  • #endregion directive indicates the end of a #region block.
  • Syntax:
     #region region-description codes #endregion

Example 6: How to use #region directive?

 using System; namespace Directive ( class Region ( public static void Main(string() args) ( #region Hello Console.WriteLine("Hello"); Console.WriteLine("Hello"); Console.WriteLine("Hello"); Console.WriteLine("Hello"); Console.WriteLine("Hello"); #endregion ) ) ) 

When we run the program, the output will be:

 Hello Hello Hello Hello Hello

#pragma directive

  • The #pragma directive is used to give the compiler some special instructions for the compilation of the file in which it appears.
  • The instruction may include disabling or enabling some warnings.
  • C# supports two #pragma instructions:
    • #pragma warning: Used for disabling or enabling warnings
    • #pragma checksum: It generates checksums for source files which will be used for debugging.
  • Syntax:
     #pragma pragma-name pragma-argumenty
  • Například:
     #pragma varování zakázáno

Příklad 7: Jak používat direktivu #pragma?

 using System; namespace Directive ( class Error ( public static void Main(string() args) ( #pragma warning disable #warning This is a warning 1 #pragma warning restore #warning This is a warning 2 ) ) ) 

Když spustíme program, výstup bude:

 Program.cs (12,22): warning CS1030: #warning: 'This is a warning 2' (/home/myuser/csharp/directive-project/directive-project.csproj)

Vidíme, že na obrazovce výstupu se zobrazí pouze druhé varování .

Důvodem je, že jsme zpočátku deaktivovali všechna varování před prvním varováním a obnovili je až před druhým varováním. Z tohoto důvodu bylo první varování skryto.

Můžeme také deaktivovat konkrétní varování namísto všech varování.

Další informace o tom #pragmanajdete na #pragma (C # reference).

Zajímavé články...