C#枚举例子:
1 public enum DepotType 2 { 3 [Description("原材料仓")] Material, 4 [Description("半成品仓")] Process, 5 [Description("成品仓")] Finished 6 }
获取枚举描述代码:
1 public class EnumKit 2 { 3 public static SortedList<int, string> GetItems<T>() 4 { 5 var result = new SortedList<int, string>(); 6 Type t = typeof(T); 7 Array arrays = Enum.GetValues(t); 8 for (int i = 0; i < arrays.LongLength; i++) 9 { 10 object test = arrays.GetValue(i); 11 FieldInfo fieldInfo = test.GetType().GetField(test.ToString()); 12 object[] attribArray = fieldInfo.GetCustomAttributes(false); 13 DescriptionAttribute attrib = (DescriptionAttribute)attribArray[0]; 14 result.Add(Convert.ToInt32(test), attrib.Description); 15 } 16 return result; 17 } 18 19 }
1 public static string GetEnumDescription(Enum enumValue) 2 { 3 string value = enumValue.ToString(); 4 FieldInfo field = enumValue.GetType().GetField(value); 5 object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性 6 if (objs.Length == 0) //当描述属性没有时,直接返回名称 7 return value; 8 DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0]; 9 return descriptionAttribute.Description; 10 }