Các lệnh tiền xử lý C #

Trong hướng dẫn này, chúng ta sẽ tìm hiểu về Chỉ thị tiền xử lý, các chỉ thị có sẵn trong C # và khi nào, tại sao và tại sao chúng được sử dụng.

Như cái tên đã giải thích, chỉ thị tiền xử lý là một khối các câu lệnh được xử lý trước khi quá trình biên dịch thực sự bắt đầu. Các chỉ thị tiền xử lý C # là các lệnh cho trình biên dịch ảnh hưởng đến quá trình biên dịch.

Các lệnh này chỉ định phần nào của mã cần biên dịch hoặc cách xử lý các lỗi và cảnh báo cụ thể.

Chỉ thị tiền xử lý C # bắt đầu bằng một # (hash)ký hiệu và tất cả các chỉ thị tiền xử lý đều tồn tại trên một dòng. Các chỉ thị tiền xử lý được kết thúc bằng new linethay vì semicolon.

Các chỉ thị tiền xử lý có sẵn trong C # là:

Các chỉ thị tiền xử lý trong C #
Chỉ thị về tiền xử lý Sự miêu tả Cú pháp
#if Kiểm tra xem một biểu thức tiền xử lý có đúng hay không
 #if mã biểu thức tiền xử lý để biên dịch #endif
#elif Được sử dụng cùng với #ifđể kiểm tra nhiều biểu thức tiền xử lý
 mã #if tiền xử lý-biểu thức-1 để biên dịch mã #elif tiền xử lý-biểu thức-2 để biên dịch #endif
#else Được sử dụng cùng với #ifđể tạo chỉ thị điều kiện phức hợp.
 #if mã biểu thức tiền xử lý để biên dịch # mãelif để biên dịch #endif
#endif Được sử dụng cùng với #ifđể biểu thị sự kết thúc của một chỉ thị có điều kiện
 #if mã biểu thức tiền xử lý để biên dịch #endif
#define Được sử dụng để xác định một ký hiệu
 #define BIỂU TƯỢNG
#undef Được sử dụng để hủy xác định một biểu tượng
 #undef BIỂU TƯỢNG
#warning Cho phép chúng tôi tạo cảnh báo cấp độ 1 từ mã của chúng tôi
 # cảnh báo-thông báo
#error Cho phép chúng tôi tạo ra lỗi từ mã của chúng tôi
 #error error-message
#line Cho phép chúng tôi sửa đổi số dòng và tên tệp của trình biên dịch để hiển thị lỗi và cảnh báo
 #line dòng-số tệp-tên
#region Cho phép chúng tôi tạo một vùng có thể được mở rộng hoặc thu gọn khi sử dụng Trình chỉnh sửa mã Visual Studio
 # vùng miền-mã mô tả vùng #endregion
#endregion Cho biết phần cuối của một vùng
 # vùng miền-mã mô tả vùng #endregion
#pragma Cung cấp cho trình biên dịch các hướng dẫn đặc biệt để biên dịch tệp mà nó xuất hiện.
 #pragma pragma-tên pragma-đối số

#define chỉ thị

  • Các #definechỉ thị cho phép chúng ta xác định một biểu tượng.
  • Các ký hiệu được xác định khi sử dụng cùng với #ifchỉ thị sẽ đánh giá là true.
  • Các ký hiệu này có thể được sử dụng để chỉ định các điều kiện để biên dịch.
  • Cú pháp:
     #define BIỂU TƯỢNG
  • Ví dụ:
     #define KIỂM TRA
    Ở đây, TESTING là một biểu tượng.

#undef chỉ thị

  • Lệnh #undefnày cho phép chúng ta hoàn tác ký hiệu.
  • Các ký hiệu không xác định khi được sử dụng cùng với #ifchỉ thị sẽ đánh giá là sai.
  • Cú pháp:
     #undef BIỂU TƯỢNG
  • Ví dụ:
     #undef KIỂM TRA
    Ở đây, TESTING là một biểu tượng.

#if chỉ thị

  • Các #ifchỉ thị được sử dụng để kiểm tra các biểu hiện tiền xử lý.
  • Một biểu thức tiền xử lý có thể chỉ bao gồm một ký hiệu hoặc kết hợp các ký hiệu cùng với các toán tử như &&(AND), ||(OR), !(NOT).
  • #ifchỉ thị được theo sau bởi một #endifchỉ thị.
  • Các mã bên trong #ifchỉ thị chỉ được biên dịch nếu biểu thức được kiểm tra với các #ifđánh giá là true.
  • Cú pháp:
     #if mã biểu thức tiền xử lý để biên dịch <#endif
  • Ví dụ:
    #if KIỂM TRA Console.WriteLine ("Đang Kiểm tra"); #endif

Ví dụ 1: Cách sử dụng chỉ thị #if?

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

Khi chúng tôi chạy chương trình, kết quả đầu ra sẽ là:

 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-tên pragma-đối số
  • Ví dụ:
     #pragma cảnh báo tắt

Ví dụ 7: Cách sử dụng chỉ thị #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 ) ) ) 

Khi chúng tôi chạy chương trình, kết quả đầu ra sẽ là:

 Program.cs (12,22): warning CS1030: #warning: 'Đây là cảnh báo 2' (/home/myuser/csharp/directive-project/directive-project.csproj)

Chúng ta có thể thấy rằng chỉ có cảnh báo thứ hai được hiển thị trên màn hình đầu ra.

Điều này là do, ban đầu chúng tôi đã tắt tất cả các cảnh báo trước cảnh báo đầu tiên và chỉ khôi phục chúng trước cảnh báo thứ hai. Đây là lý do tại sao cảnh báo đầu tiên bị ẩn.

Chúng tôi cũng có thể tắt cảnh báo cụ thể thay vì tất cả cảnh báo.

Để tìm hiểu thêm #pragma, hãy truy cập #pragma (tham chiếu C #).

thú vị bài viết...