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

從模擬字串枚舉談起:C# 中實現類似字串枚舉的最佳實踐

     編輯:關於C#

問題起因

枚舉底層僅支援整數型別(byte, int, long 等),不支援 string 或 double。但實務上常需將枚舉成員關聯字串值(如顏色 #FF0000)。

模擬方案:強型別字串常數類

public class Color {
    private Color(string value) => m_Value = value;

    public static explicit operator string(Color c) => c.m_Value;
    public static explicit operator Color(string s) {
        return s switch {
            "#FF0000" => Red,
            "#00FF00" => Green,
            "#0000FF" => Blue,
            _ => throw new InvalidCastException()
        };
    }
    public override string ToString() => m_Value;

    public static readonly Color Red = new Color("#FF0000");
    public static readonly Color Green = new Color("#00FF00");
    public static readonly Color Blue = new Color("#0000FF");

    private readonly string m_Value;
}

用法示範

Color c1 = Color.Red;
string hex = (string)c1;           // "#FF0000"
Color c2 = (Color)"#00FF00";       // Color.Green
Debug.Assert(c2 == Color.Green);   // 參考相等,無需覆寫 Equals

設計缺陷與 SRP 違反

此類同時承擔「枚舉標識」與「資料載體」雙重職責:

  • 需擴充 Alpha 通道?
  • 需提取 ARGB 分量?
  • 需 RGB⇄CMYK 轉換?
  • 1600 萬種顏色如何維護?

違反單一職責原則,難以演進。

.NET Framework 正統解法

System.Drawing 命名空間三大件:

類型職責
KnownColor enum具名顏色標識(Indigo、InfoText 等),純標識無資料
Color struct資料載體,含 ARGB 通道,提供運算、比較、轉換
ColorTranslator專責 Color ⇄ HTML 字串(#FF0000)轉換

組合使用範例

string html = ColorTranslator.ToHtml(
    Color.FromKnownColor(KnownColor.Desktop)
); // 取得桌面背景色的 HTML 字串

結論

模擬字串枚舉可用於簡單場景,但涉及豐富資料操作時,應採用職責分離的標準庫模式:枚舉做標識、結構做資料、工具類做轉換。

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