最近在做一個學校的系統,其中用到一些枚舉,可是在顯示下拉列表時要綁定枚舉的描述及其枚舉值時就只一個一個的默認設死,這樣不靈活。有沒有其快捷方法?搜了下百度很多相關資料有了些許眉目,代碼如下
1.首先定義枚舉,這里要做顯示學生狀態的列表,如下所示
1 /// <summary> 2 /// 學生狀態 3 /// </summary> 4 public enum StudentStatusEnum 5 { 6 /// <summary> 7 /// 在讀 8 /// </summary> 9 [Description("在讀")] 10 Study = 0, 11 12 /// <summary> 13 /// 畢業 14 /// </summary> 15 [Description("畢業")] 16 Graduate = 1, 17 18 /// <summary> 19 /// 退學 20 /// </summary> 21 [Description("退學")] 22 Leave = 2, 23 24 /// <summary> 25 /// 休學 26 /// </summary> 27 [Description("休學")] 28 Suspend = 3 29 }
2.循環取枚舉屬性,Enum.GetNames這個方法是獲取枚舉定義的屬性(如Study),Enum.GetValues這個方法是獲取枚舉定義的屬性值(如0)
1 foreach (var em in Enum.GetNames(typeof(StudentStatusEnum))) 2 { 3 var value = (int)Enum.Parse(typeof(StudentStatusEnum), em); 4 var name = ((StudentStatusEnum)Enum.Parse(typeof(StudentStatusEnum), em)).GetDescription(); 5 lst.Add(new BusinessObject { Name=name,Code=value.ToString()}); 6 }
3.GetDescription方法如下
1 public static string GetDescription(this object o) 2 { 3 return GetEnumAtribute(o); 4 } 5 6 public static string GetEnumAtribute(object obj) 7 { 8 if (obj == null) 9 return string.Empty; 10 var o = GetCustomAttribute<DescriptionAttribute>(obj); 11 if (o != null) 12 return o.Description; 13 return obj.ToString(); 14 } 15 16 public static ATT GetCustomAttribute<ATT>(object o) where ATT : Attribute 17 { 18 if (o == null) 19 return default(ATT); 20 System.Reflection.FieldInfo f = o.GetType().GetField(o.ToString()); 21 if (f == null) 22 return default(ATT); 23 var a = f.GetCustomAttributes(typeof(ATT), true).FirstOrDefault(); 24 if (a == null) 25 return default(ATT); 26 else 27 return (ATT)a; 28 }
完畢!!!