[C#] 取得列舉 名稱 (Get Enum Name)
實作:
*需求:
(1)需要取得列舉的名稱(Name)
(2)依相對應的列舉,將Int 轉換為列舉的名稱(Name)
1.列舉內容
public enum TestEnum { [Display(Name = "A", Description = "A")] A, [Display(Name = "B", Description = "B")] B }
2.建立一個 Enum-Helper
/// <summary> /// Enum-Helper /// </summary> public static class EnumHelper { /// <summary> /// 取得列舉名稱 /// </summary> /// <param name="obj">列舉物件</param> /// <returns></returns> public static string GetName(this Enum obj) { var objName = obj.ToString(); var t = obj.GetType(); var fi = t.GetField(objName); var arrayDescription = (DisplayAttribute[])fi.GetCustomAttributes(typeof(DisplayAttribute), false); return arrayDescription == null ? string.Empty : arrayDescription[0].Name; } /// <summary> /// 取得列舉名稱 /// </summary> /// <typeparam name="T">列舉類型</typeparam> /// <param name="obj">列舉數字</param> /// <returns></returns> public static string GetName<T>(this object obj) { if (obj == null) { return string.Empty; } if (!int.TryParse(obj.ToString(), out int value)) { value = 0; } var e = Enum.Parse(typeof(T), Convert.ToString(value)); return ((Enum)e).GetName(); } }
留言
張貼留言