問題描述:學習
以下圖所示,文章位置是枚舉值,生成右邊的下拉框。this
最終選擇解決方案:spa
使用以下方法能夠把須要的枚舉屬性生成字典而後再使用。.net
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; }
我所使用場景:3d
捨棄的解決方案:blog
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; }
此種方案生成的結果以下圖:ip
很顯然不符合項目要求,故舍棄。string
最後附上一個我經常使用的獲取枚舉值的描述特性信息的方法:it
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(); }
該方法使用場景:枚舉類型值直接調用-->由於是枚舉的擴展方法! io
PS:若是以上有任何錯誤望各位大牛不吝賜教,同時若是有更好的方法來實現望各位多多留言,互相探討學習。
【參考文章】http://blog.csdn.net/razorluo/article/details/42707331