using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace EntrustSettle.Common.Extensions { /// /// 枚举的扩展方法 /// public static class EnumExtensions { /// /// 获取到对应枚举的描述-没有描述信息,返回枚举值 /// /// /// public static string EnumDescription(this Enum @enum) { Type type = @enum.GetType(); string name = Enum.GetName(type, @enum); if (name == null) { return null; } FieldInfo field = type.GetField(name); if (!(Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attribute)) { return name; } return attribute?.Description; } public static int ToEnumInt(this Enum e) { try { return e.GetHashCode(); } catch (Exception) { return 0; } } public static List EnumToList() { return setEnumToList(typeof(T)); } public static List EnumToList(Type enumType) { return setEnumToList(enumType); } private static List setEnumToList(Type enumType) { List list = new List(); foreach (var e in Enum.GetValues(enumType)) { EnumDto m = new(); object[] attacheds = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(EnumAttachedAttribute), true); if (attacheds != null && attacheds.Length > 0) { EnumAttachedAttribute aa = attacheds[0] as EnumAttachedAttribute; //m.Attached = aa; m.TagType = aa.TagType; m.Description = aa.Description; m.Icon = aa.Icon; m.IconColor = aa.IconColor; } m.Value = Convert.ToInt32(e); m.Name = e.ToString(); list.Add(m); } return list; } } /// /// 枚举对象 /// public class EnumDto { /// /// 附加属性 /// public EnumAttachedAttribute Attached { get; set; } /// /// 标签类型 /// public string TagType { get; set; } /// /// 枚举描述 /// public string Description { get; set; } /// /// 枚举名称 /// public string Name { get; set; } /// /// 枚举值 /// public int Value { get; set; } /// /// 图标 /// public string Icon { get; set; } /// /// 图标颜色 /// public string IconColor { get; set; } } }