c# Enum获取name,value和description
如果我们的枚举类型结构如下,我们需要获取enum的name,value以及description
public enum EnumTest { [Description("Attribute")] Attribute1 = 1, [Description("Attribute")] Attribute2 = 2, [Description("Measure")] Measure1 = 3, [Description("Measure")] Measure2 = 4 }
获取的函数代码如下:
/// <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(this 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; }
根据enum的name获取description
/// <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>(this 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(); } }