Директиви за препроцесор на C #

В този урок ще научим за директивите на препроцесора, наличните директиви в C # и кога, защо и как защо се използват.

Както името оправдава, директивите на препроцесора са блок от изрази, който се обработва преди действителната компилация да започне. Директивите за препроцесор на C # са командите за компилатора, които засягат процеса на компилация.

Тези команди указват кои раздели на кода да се компилират или как да се справят с конкретни грешки и предупреждения.

Директивата за препроцесор на C # започва със # (hash)символ и всички директиви за препроцесор продължават за един ред. Препроцесорните директиви се прекратяват по- new lineскоро от semicolon.

Директивите за препроцесор, налични в C #, са:

Препроцесорни директиви в C #
Директива за препроцесора Описание Синтаксис
#if Проверява дали изразът на препроцесор е верен или не
 #if код на препроцесор-израз за компилиране #endif
#elif Използва се заедно с #ifза проверка на множество изрази на препроцесор
 #if код на препроцесор-израз-1 за компилация #elif код на препроцесор-израз-2 за компилиране #endif
#else Използва се заедно с #ifза създаване на съставна условна директива.
 #if код на препроцесор-израз за компилация #elif код за компилиране #endif
#endif Използва се заедно с, за #ifда посочи края на условна директива
 #if код на препроцесор-израз за компилиране #endif
#define Използва се за дефиниране на символ
 #define SYMBOL
#undef Използва се за недефиниране на символ
 #undef СИМВОЛ
#warning Позволява ни да генерираме предупреждение от ниво 1 от нашия код
 # предупреждение-предупреждение-съобщение
#error Позволява ни да генерираме грешка от нашия код
 #error съобщение за грешка
#line Позволява ни да модифицираме номера на реда и името на компилатора, за да показваме грешки и предупреждения
 # ред-номер на ред-име на файл
#region Позволява ни да създадем регион, който може да бъде разширен или свит при използване на редактор на кодове на Visual Studio
 #region регион-кодове за описание #endregion
#endregion Показва края на регион
 #region регион-кодове за описание #endregion
#pragma Дава на компилатора специални инструкции за компилирането на файла, в който се появява.
 #pragma pragma-name pragma-аргументи

#define директива

  • В #defineдирективата ни позволява да се определи символ.
  • Символите, които се дефинират, когато се използват заедно с #ifдирективата, ще бъдат оценени като истина.
  • Тези символи могат да се използват за определяне на условия за компилация.
  • Синтаксис:
     #define SYMBOL
  • Например:
     #define TESTING
    Тук ИЗПИТВАНЕТО е символ.

директива #undef

  • В #undefдирективата ни позволява отменянето на дефиницията символ.
  • Недефинираните символи, когато се използват заедно с #ifдирективата, ще бъдат оценени като false.
  • Синтаксис:
     #undef СИМВОЛ
  • Например:
     #undef ТЕСТИРАНЕ
    Тук ИЗПИТВАНЕТО е символ.

#if директива

  • В #ifдирективата се използва за тестване на изразяването на предпроцесорни.
  • Предпроцесорният израз може да се състои само от символ или комбинация от символи заедно с оператори като &&(И), ||(ИЛИ), !(НЕ).
  • #ifдиректива е последвана от #endifдиректива.
  • Кодовете вътре в #ifдирективата се компилират само ако изразът, тестван с #ifоценява на true.
  • Синтаксис:
     #if код на препроцесор-израз за компилиране <#endif
  • Например:
    #if ИЗПИТВАНЕ Console.WriteLine ("В момента се тества"); #endif

Пример 1: Как да използвам директивата #if?

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

Когато стартираме програмата, изходът ще бъде:

 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-аргументи
  • Например:
     #pragma предупреждение забранено

Пример 7: Как да използвам директивата #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 ) ) ) 

Когато стартираме програмата, изходът ще бъде:

 Program.cs (12,22): предупреждение CS1030: #warning: 'Това е предупреждение 2' (/home/myuser/csharp/directive-project/directive-project.csproj)

Виждаме, че на изходния екран се показва само второто предупреждение .

Това е така, защото първоначално деактивирахме всички предупреждения преди първото предупреждение и ги възстановихме само преди второто предупреждение. Това е причината първото предупреждение да е скрито.

Също така можем да деактивираме конкретно предупреждение вместо всички предупреждения.

За да научите повече за #pragma, посетете #pragma (справка за C #).

Интересни статии...