// 枚举 public enum enumStudent { [Description("性别")] sex = 0, [Description("年龄")] age = 1, } // 获取方法 public string GetDescriptionByEnum(Enum enumValue) { string value = enumValue.ToString(); System.Reflection.FieldInfo field = enumValue.GetType().GetField(value); object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性 if (objs.Length == 0) //当描述属性没有时,直接返回名称 return value; DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0]; return descriptionAttribute.Description; } // 调用示例 GetDescriptionByEnum(enumStudent.age) → 年龄 public T GetEnumByDescription<T>(string description) where T : Enum { System.Reflection.FieldInfo[] fields = typeof(T).GetFields(); foreach(System.Reflection.FieldInfo field in fields) { object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性 if (objs.Length > 0 && (objs[0] as DescriptionAttribute).Description == description) { return (T)field.GetValue(null); } } throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", description), "Description"); } // 调用示例
标签:objs,string,DescriptionAttribute,field,枚举,Description From: https://www.cnblogs.com/xiaobaicai12138/p/18112641