枚舉底層僅支援整數型別(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
此類同時承擔「枚舉標識」與「資料載體」雙重職責:
違反單一職責原則,難以演進。
System.Drawing 命名空間三大件:
| 類型 | 職責 |
|---|---|
KnownColor enum | 具名顏色標識(Indigo、InfoText 等),純標識無資料 |
Color struct | 資料載體,含 ARGB 通道,提供運算、比較、轉換 |
ColorTranslator | 專責 Color ⇄ HTML 字串(#FF0000)轉換 |
string html = ColorTranslator.ToHtml(
Color.FromKnownColor(KnownColor.Desktop)
); // 取得桌面背景色的 HTML 字串
模擬字串枚舉可用於簡單場景,但涉及豐富資料操作時,應採用職責分離的標準庫模式:枚舉做標識、結構做資料、工具類做轉換。