. Net c # obtain the enumerated value set and its attributes,
Problem description:
As shown in, the position of the article is an enumeration value, which generates a drop-down box on the right.
Finally select a solution:
You can use the following method to generate a dictionary for the required enumeration Attribute before using it.
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; }
My use cases:
Abandoned solution:
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; }
The result of this scheme is as follows:
Apparently it does not meet the project requirements, so it is discarded.
Finally, I attached a common method to obtain the descriptive feature information of enumeration values:
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(); }
This method is used in the following scenarios: directly calling Enumeration type values --> because it is an enumeration extension method!
PS: If you have any of the above errors, I hope you can give me some advice. If you have any better methods to achieve this, I hope you can leave a message and discuss and learn from each other.
[Reference] http://blog.csdn.net/razorluo/article/details/42707331