diff --git a/Blog.Core.Common/Attribute/EnumAttachedAttribute.cs b/Blog.Core.Common/Attribute/EnumAttachedAttribute.cs new file mode 100644 index 0000000..8d1ea85 --- /dev/null +++ b/Blog.Core.Common/Attribute/EnumAttachedAttribute.cs @@ -0,0 +1,28 @@ +using System; + +namespace Blog.Core.Common +{ + + [AttributeUsage(AttributeTargets.Field, Inherited = true)] + public class EnumAttachedAttribute : Attribute + { + /// + /// 标签类型 样式 + /// + public string TagType { get; set; } + /// + /// 中文描述 + /// + public string Description { get; set; } + + /// + /// 图标 + /// + public string Icon { get; set; } + + /// + /// 图标颜色 + /// + public string IconColor { get; set; } + } +} diff --git a/Blog.Core.Common/Extensions/EnumExtensions.cs b/Blog.Core.Common/Extensions/EnumExtensions.cs new file mode 100644 index 0000000..6c71488 --- /dev/null +++ b/Blog.Core.Common/Extensions/EnumExtensions.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Reflection; + +namespace Blog.Core.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; } + } +}