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

การใช้ Enum Keyword กำหนดชนิดตัวแปรใน C#

ภาพรวม

Enum (Enumeration) ใน C# เป็น Value Type ที่กำหนดชุดของ Named Constants (ค่าคงที่มีชื่อ) ใช้แทน Magic Numbers ทำให้โค้ดอ่านง่าย รักษาความปลอดภัยของชนิด (Type Safety) และช่วย IntelliSense

ไวยากรณ์

enum 
{
    Value1,
    Value2,
    Value3
}

ค่าเริ่มต้น: Value1 = 0, Value2 = 1, Value3 = 2 ... (เพิ่มทีละ 1)

ตัวอย่างพื้นฐาน

enum Vehicle { Car, Bus, Truck }; // Car=0, Bus=1, Truck=2

ตัวอย่างโปรแกรม

using System;

namespace Demo
{
    class Program
    {
        // ประกาศ Enum ภายใน Class
        enum Days 
        { 
            Sun, Mon, Tue, Wed, Thu, Fri, Sat 
        };
        
        static void Main(string[] args)
        {
            // แปลง Enum เป็น int (Underlying Type)
            int weekStart = (int)Days.Mon;  // 1
            int weekEnd = (int)Days.Fri;    // 5
            
            Console.WriteLine("Monday: {0}", weekStart);
            Console.WriteLine("Friday: {0}", weekEnd);
            
            // ใช้ Enum โดยตรง
            Days today = Days.Wed;
            Console.WriteLine("วันนี้: " + today);        // Wed
            Console.WriteLine("ค่าตัวเลข: " + (int)today); // 3
            
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Monday: 1
Friday: 5
วันนี้: Wed
ค่าตัวเลข: 3

คุณสมบัติขั้นสูงของ Enum

1. กำหนดค่าเอง (Explicit Values)

enum HttpStatus
{
    OK = 200,
    NotFound = 404,
    ServerError = 500
}

2. กำหนด Underlying Type (Default: int)

enum Priority : byte  // ใช้ byte (0-255) ประหยัดหน่วยความจำ
{
    Low = 1,
    Medium = 2,
    High = 3
}

3. Flags Attribute (Bitwise Flags)

[Flags]
enum FileAccess
{
    None = 0,
    Read = 1,      // 0001
    Write = 2,     // 0010
    Execute = 4,   // 0100
    ReadWrite = Read | Write // 0011 = 3
}

// ใช้งาน
FileAccess access = FileAccess.Read | FileAccess.Write; // 3
bool canRead = (access & FileAccess.Read) != 0;         // true
bool canExec = (access & FileAccess.Execute) != 0;      // false

4. เมธอด Enum Class ที่มีประโยชน์

// Parse String -> Enum
Days d = (Days)Enum.Parse(typeof(Days), "Mon");     // Old way
Days d2 = Enum.Parse("Mon");                  // C# 7.1+

// TryParse (ปลอดภัยกว่า)
if (Enum.TryParse("Invalid", out Days result))
    Console.WriteLine(result);

// Get Names/Values
string[] names = Enum.GetNames(typeof(Days));       // ["Sun", "Mon", ...]
Array values = Enum.GetValues(typeof(Days));        // [0, 1, 2, 3, 4, 5, 6]

// Check defined
bool defined = Enum.IsDefined(typeof(Days), 3);     // true (Wed)
bool defined2 = Enum.IsDefined(typeof(Days), 10);   // false

ข้อสังเกตสำคัญ

  • Enum เป็น Value Type - เก็บใน Stack, Copy by Value
  • Underlying Type ใดๆ ได้: byte, sbyte, short, ushort, int, uint, long, ulong
  • Cast ระหว่าง Enum และ Underlying Type ได้โดยตรง: (int)Days.Mon
  • [Flags] Attribute ทำให้ ToString() แสดงแบบ Combined: "Read, Write"
  • หลีกเลี่ยงการ Cast Int ตรงๆ เข้า Enum ที่ไม่ได้ Define (Undefined Behavior)
  • ใช้ nameof(Enum.Value) ได้ใน C# 6+