問題描述:
如下圖所示,文章位置是枚舉值,生成右邊的下拉框。
最終選擇解決方案:
使用如下方法可以把需要的枚舉屬性生成字典然后再使用。
public static Dictionary<int, string> EnumToDictionary<T>() { Dictionary<int, string> dic = new Dictionary<int, string>(); if (!typeof(T).IsEnum) { return dic; } string desc = string.Empty; foreach (var item in Enum.GetValues(typeof(T))) { var attrs = item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true); if (attrs != null && attrs.Length > 0) { DescriptionAttribute descAttr = attrs[0] as DescriptionAttribute; desc = descAttr.Description; } dic.Add(Convert.ToInt32(item), desc); } return dic; }
我所使用場景:
舍棄的解決方案:
public static List<T> EnumToList<T>() { List<T> list = new List<T>(); foreach (var item in Enum.GetValues(typeof(T))) { list.Add((T)item); } return list; }
此種方案生成的結果如下圖:
很顯然不符合項目要求,故舍棄。
最后附上一個我常用的獲取枚舉值的描述特性信息的方法:
public static string GetDescription(this Enum obj) { return GetDescription(obj, false); } private static string GetDescription(this Enum obj, bool isTop) { if (obj == null) { return string.Empty; } try { Type _enumType = obj.GetType(); DescriptionAttribute dna = null; if (isTop) { dna = (DescriptionAttribute)Attribute.GetCustomAttribute(_enumType, typeof(DescriptionAttribute)); } else { FieldInfo fi = _enumType.GetField(Enum.GetName(_enumType, obj)); dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute)); } if (dna != null && string.IsNullOrEmpty(dna.Description) == false) return dna.Description; } catch { return string.Empty; } return obj.ToString(); }
該方法使用場景:枚舉類型值直接調用-->因為是枚舉的擴展方法!
PS:如果以上有任何錯誤望各位大牛不吝賜教,同時如果有更好的方法來實現望各位多多留言,互相探討學習。
【參考文章】http://blog.csdn.net/razorluo/article/details/42707331