枚舉類型為一組相關符號常數定義類型名稱,用於「多項選擇」場合:運行時從編譯時固定的選項集合中決策。本文對應規范第 1.11 節「枚舉」。
enum Color
{
Red,
Blue,
Green
}
class Shape
{
public void Fill(Color color)
{
switch (color)
{
case Color.Red: /* ... */ break;
case Color.Blue: /* ... */ break;
case Color.Green: /* ... */ break;
default: break;
}
}
}
| 維度 | 整數常數 (int) | 枚舉 (enum) |
|---|---|---|
| 可讀性 | `Fill(1)` 意圖不明 | `Fill(Color.Red)` 自文檔化 |
| 類型安全 | 可傳入任意 int | 編譯期限制為定義值 |
| 工具支持 | 無智能提示 | IDE 列舉成員自動完成、重構重命名 |
| 除錯體驗 | 顯示數字 | 顯示符號名 (Color.Red) |
| 命名空間 | 污染全局/類作用域 | 獨立作用域 (Color.Red) |
enum Color { Red, Blue, Green } // 0, 1, 2
enum Color { Red = 1, Blue, Green } // 1, 2, 3
enum Color { Red = 1, Blue = 4, Green } // 1, 4, 5 (Green 自動 +1)
enum Flags { None = 0, Read = 1, Write = 2, Execute = 4 } // 位標誌
[Flags]
enum FileAccess
{
None = 0,
Read = 1,
Write = 2,
ReadWrite = Read | Write, // 3
Execute = 4
}
// 使用
FileAccess access = FileAccess.Read | FileAccess.Write; // 組合
bool canRead = (access & FileAccess.Read) != 0; // 位檢查
Console.WriteLine(access); // 輸出 "Read, Write" (Flags 效果)
Color c = Color.Red;
int i = (int)c; // 0
Color c2 = (Color)1; // Blue (無運行時檢查!)
bool defined = Enum.IsDefined(typeof(Color), 1); // true
string name = c.ToString(); // "Red"
Color parsed = (Color)Enum.Parse(typeof(Color), "Blue"); // Blue
枚舉是 C# 建模「有限選項集」的標準方式。它以類型安全、自文檔化、工具友好、除錯可讀四大優勢,完勝整數常數。掌握底層類型選擇、自動/手動賦值、位標誌模式、FlagsAttribute、解析轉換,能讓領域模型更精準、代碼更健壯。