枚举相关(根据枚举值获取枚举描述,获取枚举的描述)
public enum AccountType { [Description("普通账户")] Ordinary= 1, [Description("重要账户")] Important= 2 }
#region 枚举相关 /// <summary> /// 获取枚举的描述 /// </summary> /// <param name="enumValue">枚举值</param> /// <returns></returns> public static string GetDescription(this Enum enumValue) { string value = enumValue.ToString(); FieldInfo field = enumValue.GetType().GetField(value); //获取描述属性 DescriptionAttribute descriptionAttribute = field.GetCustomAttribute<DescriptionAttribute>(); //当描述属性没有设置时,直接返回名称 return descriptionAttribute != null ? descriptionAttribute.Description : value; } /// <summary> /// 获取枚举StringValue /// </summary> /// <param name="enumValue"></param> /// <returns></returns> public static string GetStringValue(this Enum enumValue) { string output = null; System.Type type = enumValue.GetType(); System.Reflection.FieldInfo fi = type.GetField(enumValue.ToString()); StringValue[] attrs = fi.GetCustomAttributes(typeof(StringValue), false) as StringValue[]; if (attrs.Length > 0) { output = attrs[0].Value; } return output; } /// <summary> /// 根据枚举值,获取描述 /// </summary> /// <param name="enumValue"></param> /// <returns></returns> public static string GetEnumDesc(this Enum enumValue) { string value = enumValue.ToString(); FieldInfo field = enumValue.GetType().GetField(value); object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性 if (objs == null || objs.Length == 0) //当描述属性没有时,直接返回名称 return value; DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0]; return descriptionAttribute.Description; } #endregion