using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Services.Extensions { /// /// 枚举扩展 /// public static class EnumerableExtensions { /// /// 对枚举器的每个元素执行指定的操作 /// /// 枚举器类型参数 /// 枚举器 /// 要对枚举器的每个元素执行的委托 public static void ForEach(this IEnumerable source, Action action) { if (source.IsNullOrEmpty() || action == null) { return; } foreach (T obj in source) { action(obj); } } /// /// 指示指定的枚举器是null还是没有任何元素 /// /// 枚举器类型参数 /// 要测试的枚举器 /// true:枚举器是null或者没有任何元素 false:枚举器不为null并且包含至少一个元素 public static bool IsNullOrEmpty(this IEnumerable source) { return source == null || !source.Any(); } /// /// 得到枚举中文备注 /// /// /// public static string GetEnumDesc(this System.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; } public static string GetEnumDesc(this Type enumType, object val) { string enumvalue = Enum.GetName(enumType, val); if (string.IsNullOrEmpty(enumvalue)) { return ""; } FieldInfo finfo = enumType.GetField(enumvalue); object[] enumAttr = finfo.GetCustomAttributes(typeof(DescriptionAttribute), true); if (enumAttr.Length > 0) { DescriptionAttribute desc = (DescriptionAttribute)enumAttr[0]; if (desc != null) { return desc.Description; } } return enumvalue; } /// /// 获取所有的枚举描述和值 /// /// /// public static List GetEnumListItem(this Type type) { List list = new List(); // 循环枚举获取所有的Fields foreach (var field in type.GetFields()) { // 如果是枚举类型 if (field.FieldType.IsEnum) { object tmp = field.GetValue(null); Enum enumValue = (Enum)tmp; int intValue = Convert.ToInt32(enumValue); string showName = enumValue.GetEnumDesc(); // 获取描述和排序 list.Add(new EnumDto { Value = intValue, Description = showName }); } } //返回 return list; } public class EnumDto { /// /// 枚举code /// public string Code { get; set; } /// /// 值 /// public int Value { get; set; } /// /// 描述 /// public string Description { get; set; } } } }