只有累積,沒有奇蹟

2018年12月11日 星期二

[.NET] 如何取得 Enum 的 Description 描述字串

前言 
列舉類型 Enum 在 C# 很常用的一種類型所允許的型別必須是byte、sbyte、short、ushort、int、uint、long、ulong在使用上沒特別指定的話基本類型是 int,對我自己來說在程式中使用 Enum 而不用 int 的好處是 Code 閱讀上比較清晰,舉例來說在閱讀代碼時第一段代碼使用 Enum 更容易讓人好懂些
  1. if (code == ResponseCode.OK)
  2. //todo
  3.  
  4. if (code2 == 500)
  5. // 500是蝦米
在使用上可以於 Enum 加上 DescriptionAttribute 加上列舉值的描述,這篇文章簡單紀錄如何取得 Enum 自定義的 Description 描述的字串

作法 : 擴充方法 (Extension Method) + 反射 (Reflection)
針對 Enum 類型加上 GetDescriptionText 的擴充方法,讓使用端可以方便使用擴充方法說明可以參考 MSDN 說明不囉嗦直接看 Code
  1. // 取得 Enum 列舉 Attribute Description 設定值
  2. public static string GetDescriptionText(this T source)
  3. {
  4. FieldInfo fi = source.GetType().GetField(source.ToString());
  5. DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
  6. typeof(DescriptionAttribute), false);
  7. if (attributes.Length > 0) return attributes[0].Description;
  8. else return source.ToString();
  9. }
使用方式
  1. public enum Days
  2. {
  3. [Description("今天星期日 End")]
  4. Sun,
  5. [Description("今天星期一 猴子穿新衣")]
  6. Mon,
  7. [Description("今天星期二 猴子肚子餓")]
  8. Tue,
  9. [Description("今天星期三 猴子去爬山")]
  10. Wed,
  11. [Description("今天星期四 猴子去考試")]
  12. Thu,
  13. [Description("今天星期五 猴子去跳舞")]
  14. Fri,
  15. [Description("今天星期六 猴子去斗六")]
  16. Sat
  17. }
  18.  
  19. static void Main()
  20. {
  21. Console.WriteLine(Days.Mon.GetDescriptionText());
  22. }
  23.  
  24. // print : 今天星期一 猴子穿新衣
後續
這段Code每次建新專案都會用到一次,但都懶得紀錄就每次都google
克服自己的懶惰終於把他記起來了 XD

參考
Get Description Attributes From a Flagged Enum
Getting attributes of Enum's value
擴充方法 (C# 程式設計手冊)

1 則留言:

Copyright © 2025 m@rcus 學習筆記 | Powered by Blogger

Design by Anders Noren | Blogger Theme by NewBloggerThemes.com