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

Conditional Pre-processor Directive ใน C#

Conditional Pre-processor Directives ใน C#

Pre-processor Directives เริ่มต้นด้วย # ใช้ควบคุมการคอมไพล์ (Conditional Compilation) ไม่ใช่ Statement ปกติ (ไม่มี Semicolon)

Directives หลัก

Directiveคำอธิบาย
#define SYMBOLกำหนด Symbol (Conditional Compilation Symbol)
#undef SYMBOLยกเลิก Symbol
#if SYMBOLเริ่มเงื่อนไข (True = Compile code block)
#elif SYMBOLElse-if สำหรับ Preprocessor
#elseElse Block
#endifจบเงื่อนไข #if
#warning TEXTแสดง Warning ใน Compiler Output
#error TEXTแสดง Error หยุด Compilation
#region/#endregionจัดกลุ่มโค้ดใน IDE (Collapsible)

Operators ใน #if

  • == (Equality), != (Inequality)
  • && (AND), || (OR)
  • ! (NOT)

ตัวอย่างครบถ้วน


#define DEBUG
#define VC_V10

using System;

public class Demo
{
    public static void Main()
    {
#if (DEBUG && !VC_V10)
        Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V10)
        Console.WriteLine("VC_V10 is defined");
#elif (DEBUG && VC_V10)
        Console.WriteLine("DEBUG and VC_V10 are defined");
#else
        Console.WriteLine("DEBUG and VC_V10 are not defined");
#endif
        
        Console.ReadKey();
    }
}

ผลลัพธ์


DEBUG and VC_V10 are defined

การใช้งานจริง (Real-world)


// 1. Debug Logging
#if DEBUG
    Console.WriteLine($"Debug: User {userId} logged in at {DateTime.Now}");
#endif

// 2. Platform-specific Code
#if NETFRAMEWORK
    // .NET Framework only code
#elif NETCOREAPP
    // .NET Core / .NET 5+ only code
#endif

// 3. Feature Flags
#define ENABLE_NEW_UI
#if ENABLE_NEW_UI
    // New UI Code
#else
    // Legacy UI Code
#endif

// 4. Prevent Compiler Optimization Removal
#if DEBUG
    public void DebugOnlyMethod() { ... }
#endif

Define Symbols ใน Project Settings

แทนที่จะ #define ในโค้ด ให้ตั้งค่าใน Project Properties → Build → Conditional compilation symbols (เช่น DEBUG;TRACE;MY_FEATURE)