如果我们的枚举类型结构如下,我们需要获取enum的name,value以及description
public enum EnumTest { [Description("Attribute")] Attribute1 = 1, [Description("Attribute")] Attribute2 = 2, [Description("Measure")] Measure1 = 3, [Description("Measure")] Measure2 = 4 }
获取的函数代码如下:
public class EnumHelper { ////// get all information of enum,include value,name and description /// /// the type of enumName ///public static List GetAllItems(Type enumName) { List list = new List (); // get enum fileds FieldInfo[] fields = enumName.GetFields(); foreach (FieldInfo field in fields) { if (!field.FieldType.IsEnum) { continue; } // get enum value int value = (int)enumName.InvokeMember(field.Name, BindingFlags.GetField, null, null, null); string text = field.Name; string description = string.Empty; object[] array = field.GetCustomAttributes(typeof(DescriptionAttribute), false); if (array.Length > 0) { description = ((DescriptionAttribute)array[0]).Description; } else { description = ""; //none description,set empty } //add to list dynamic obj = new ExpandoObject(); obj.Value = value; obj.Text = text; obj.Description = description; list.Add(obj); } return list; } /// /// get enum description by name /// ///enum type /// the enum name ///public static string GetDescriptionByName (T enumItemName) { FieldInfo fi = enumItemName.GetType().GetField(enumItemName.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes( typeof(DescriptionAttribute), false); if (attributes != null && attributes.Length > 0) { return attributes[0].Description; } else { return enumItemName.ToString(); } } }