public class EnumHelper { /// <summary> /// get all information of enum,include value,name and description /// </summary> /// <param name="enumName">the type of enumName</param> /// <returns></returns> public static List<dynamic> GetAllItems(Type enumName) { List<dynamic> list = new List<dynamic>(); // 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; } public static List<string> GetEnumDescriptions(Type enumType) { List<string> nameList = new List<string>(); foreach (var e in Enum.GetValues(enumType)) { // 转换成Description后添加至List object objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true)[0]; nameList.Add((objArr as DescriptionAttribute).Description); } return nameList; } /// <summary> /// get enum description by name /// </summary> /// <typeparam name="T">enum type</typeparam> /// <param name="enumItemName">the enum name</param> /// <returns></returns> public static string GetDescriptionByName<T>(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(); } } }
调用
public enum CameraIndex { [Description("入料定位相机")] MoveInCamera, [Description("异物检测相机")] RarityCamera, [Description("Sealant上检测相机")] SealantUpCamera, [Description("Sealant下检测相机")] SealantButtomCamera, [Description("顶部拍照相机")] TopCamera, } List<string> strList = EnumHelper.GetEnumDescriptions(typeof(CameraIndex)); List<dynamic> data = EnumHelper.GetAllItems(typeof(CameraIndex)); CameraIndex cam = CameraIndex.MoveInCamera; string itemDesrip = EnumHelper.GetDescriptionByName<CameraIndex>(cam); string desp = data[0].Description; int val = data[0].Value;