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

การใช้ #if #elif #else #endif Directives ใน C#

Preprocessor Directives เริ่มด้วย # ใช้ควบคุมการ Compile แบบ Conditional (Compile-time)

Directives หลัก

  • #define SYMBOL - กำหนด Symbol
  • #undef SYMBOL - ยกเลิก Symbol
  • #if SYMBOL - ทดสอบ Symbol
  • #elif SYMBOL - Else If
  • #else - Else
  • #endif - จบเงื่อนไข

ตัวอย่าง

#define ONE
#undef TWO

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            #if (ONE && TWO)
                Console.WriteLine("Both are defined");
            #elif (ONE && !TWO)
                Console.WriteLine("ONE is defined and TWO is undefined");
            #elif (!ONE && TWO)
                Console.WriteLine("ONE is undefined and TWO is defined");
            #else
                Console.WriteLine("Both are undefined");
            #endif
        }
    }
}

ผลลัพธ์

ONE is defined and TWO is undefined

การใช้งานจริง

// Conditional Compilation สำหรับ Debug/Release
#if DEBUG
    Console.WriteLine("Debug mode: " + debugInfo);
#endif

// Platform-specific code
#if WINDOWS
    // Windows-only code
#elif LINUX
    // Linux-only code
#endif

// Feature Flags
#if PREMIUM_FEATURES
    EnablePremium();
#endif

Define Symbols ใน Project Settings

Properties → Build → Conditional compilation symbols: DEBUG;TRACE;MY_SYMBOL