using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Xml; namespace Tiger.Model.Extensions { /// /// 枚举扩展方法 /// internal static class EnumExtension { /// /// 获得枚举的名称 /// /// 枚举的名称 public static string GetName(this Enum obj) { return Enum.GetName(obj.GetType(), obj); } /// /// 获得枚举的值 /// /// 枚举的值 public static int GetValue(this Enum obj) { return Convert.ToInt32(obj); } /// /// 获得枚举的描述,如果没有定义描述则使用枚举的名称代替 /// /// 枚举的描述 public static string GetDesc(this Enum obj) { string name = Enum.GetName(obj.GetType(), obj); DescriptionAttribute attribute = obj.GetType().GetField(name).GetCustomAttribute(typeof(DescriptionAttribute), true) as DescriptionAttribute; return attribute?.Description ?? name; } /// /// 根据名称或者描述获取枚举对象 /// /// /// /// public static T GetEnum(this string description) where T : struct { Type type = typeof(T); foreach (var field in type.GetFields()) { if (field.Name == description) { return (T)field.GetValue(null); } var attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), true); if (attributes != null && attributes.FirstOrDefault() != null) { if (attributes.First().Description == description) { return (T)field.GetValue(null); } } } throw new ArgumentException($"{type.Name}中未能找到名称或者描述[{description}]对应的枚举.", "Description"); } /// /// 根据值获取枚举对象 /// /// /// /// public static T GetEnum(this int value) where T : struct { Type type = typeof(T); if (type.IsEnum) { return (T)Enum.Parse(type, value.ToString()); } throw new TypeLoadException($"{type.Name}不是枚举类型"); } /// /// 根据值获取枚举描述 /// /// /// /// public static string GetEnumDesc(this int value) where T : struct { Type type = typeof(T); if (type.IsEnum) { return GetDesc((Enum)Enum.Parse(type, value.ToString())); } throw new TypeLoadException($"{type.Name}不是枚举类型"); } /// /// 获取枚举内容列表 /// /// 枚举类型typeof(T) /// 返回枚举内容列表 public static List GetEnumContent(this Type type) { List result = new List(); FieldInfo[] fields = type.GetFields(); foreach (FieldInfo field in fields) { if (field.FieldType.IsEnum) { object[] attr = field.GetCustomAttributes(typeof(DescriptionAttribute), false); result.Add(new EnumContent(field.Name, Convert.ToInt32(field.GetValue(null)), attr.Length == 0 ? field.Name : ((DescriptionAttribute)attr[0]).Description)); } } return result; } } /// /// 枚举内容实体 /// internal readonly struct EnumContent { /// /// 枚举内容实体 /// /// 名称 /// 值 /// 描述 public EnumContent(string name, int value, string desc) { Name = name; Value = value; Desc = desc; } /// /// 名称 /// public string Name { get; } /// /// 值 /// public int Value { get; } /// /// 描述 /// public string Desc { get; } } }