首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 語言規范解讀:枚舉 —— 多項選擇的類型安全建模

     編輯:關於C語言

前言:枚舉的定位

枚舉類型為一組相關符號常數定義類型名稱,用於「多項選擇」場合:運行時從編譯時固定的選項集合中決策。本文對應規范第 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)

底層表示與進階特性

底層類型

  • 默認 `int` (32 位有符號)
  • 可顯式指定:`enum Color : byte { Red, Blue, Green }` (支持 `byte, sbyte, short, ushort, int, uint, long, ulong`)

常數值自動/手動分配


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 } // 位標誌

位標誌枚舉與 FlagsAttribute


[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

最佳實踐

  1. 單選場景用普通枚舉,互斥狀態建模
  2. 組合場景用 `[Flags]` 枚舉,位運算組合
  3. 避免無意義數字:`if (status == 2)` → `if (status == OrderStatus.Shipped)`
  4. 公開 API 慎用 `[Flags]`:新增成員會改變組合值語義,考慮版本兼容
  5. 默認值 0 表示「無/默認」:`None = 0`,便於 `default(T)` 語義

總結

枚舉是 C# 建模「有限選項集」的標準方式。它以類型安全、自文檔化、工具友好、除錯可讀四大優勢,完勝整數常數。掌握底層類型選擇、自動/手動賦值、位標誌模式、FlagsAttribute、解析轉換,能讓領域模型更精準、代碼更健壯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved