Enum列舉是實質型態(Value Type),指定的類型可以是byte, short, int和long型態。我們可以用Enum列舉來代替Magic Number(魔術數字)來做狀況判斷。例如:
var seasonName = date.Season == 1 ? “春天” : “其它季節”;
這樣的寫法難已修改。隨者專案越大,用到的魔術數字也越來越多。只要忘了改一個地方,就會產生一個新的Bug,造成維護上的困難。
我們可以用列舉(Enum)避免此狀況發生。已下是範例:


以上例子,可以新增一個 季節
的 Enum
,統一管理季節的值,這樣程式可讀性佳,要改變值也只需改一個地方。
確認0是有效的狀態
在.NET初始化實值型別時,預設的值是0。列舉也一樣: 由於此列舉從1開始,並未從0開始。0是一個無效的狀態,也許開發者會注意這情節,但接手的程式設計師未必了解這情況。


結果傳回0,並未在列舉的範圍。這樣可能會發生無法預期的錯誤,所以最好還是要確保0是有效的狀態。
結語
善加使用Enum列舉可以避免許多Bug發生,也增加了程式碼的可讀性和維護性。熟知使用Enum列舉是簡單提升程式碼品質的方法。