Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Pre-processor Directive ใน C# คืออะไร

C# Compiler ไม่มี Preprocessor แยกต่างหาก แต่ Directives จะถูกประมวลผลเหมือนมีอยู่ Preprocessor Directives ใช้ช่วยใน Conditional Compilation (การคอมไพล์แบบมีเงื่อนไข)

Preprocessor Directives ให้คำสั่งกับ Compiler ให้ประมวลผลข้อมูลก่อนการคอมไพล์จริง

รายการ Preprocessor Directives ใน C#

ลำดับDirective และ คำอธิบาย
1#define
กำหนดลำดับตัวอักษร เรียกว่า Symbol
2#undef
ยกเลิกการกำหนด Symbol
3#if
ทดสอบ Symbol ว่าเป็นจริงหรือไม่
4#else
สร้างเงื่อนไขร่วมกับ #if
5#elif
สร้างเงื่อนไขแบบทดสอบหลายเงื่อนไข
6#endif
จบเงื่อนไข Conditional Directive
7#line
เปลี่ยนหมายเลขบรรทัดและชื่อไฟล์สำหรับ Error/Warning
8#error
สร้าง Error จากตำแหน่งเฉพาะในโค้ด
9#warning
สร้าง Warning ระดับ 1 จากตำแหน่งเฉพาะ
10#region
กำหนดบล็อกโค้ดที่ย่อ/ขยายได้ใน Visual Studio
11#endregion
จบบล็อก #region

ตัวอย่าง

#define PI
using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            #if (PI)
            Console.WriteLine("PI is defined");
            #else
            Console.WriteLine("PI is not defined");
            #endif
            Console.ReadKey();
        }
    }
}