/// <summary> /// 获取枚举定义中的程序显示名称 /// </summary> /// <param name="myEnum"></param> /// <returns></returns> public static string GetDisplayName(this Enum myEnum) { Type type = myEnum.GetType(); FieldInfo info = type.GetField(myEnum.ToString()); EnumMappingAttribute spa = info.GetCustomAttributes(typeof(EnumMappingAttribute), true)[0] as EnumMappingAttribute; if (spa != null) { return(spa.DisplayName); } else { return(null); } }
/// <summary> /// 把某个显示值翻译成对应的枚举项 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="str"></param> /// <returns></returns> public static T Parse2EnumByDisplayName <T>(string str) { try { Type t = typeof(T); foreach (var fi in t.GetFields(BindingFlags.Static | BindingFlags.Public)) { EnumMappingAttribute spa = Attribute.GetCustomAttributes(fi, typeof(EnumMappingAttribute), true)[0] as EnumMappingAttribute; if (spa != null && spa.DisplayName == str) { return((T)Enum.Parse(typeof(T), fi.Name, true)); } } return(default(T)); } catch { return(default(T)); } }
/// <summary> /// 根据枚举定义中的数据库名称来判断某个数据值是否与某枚举相等 /// </summary> /// <param name="myEnum"></param> /// <param name="dbCode"></param> /// <returns></returns> public static bool EqualByDBCode(this Enum myEnum, string dbCode) { Type type = myEnum.GetType(); FieldInfo info = type.GetField(myEnum.ToString()); EnumMappingAttribute ema = info.GetCustomAttributes(typeof(EnumMappingAttribute), true)[0] as EnumMappingAttribute; if (ema != null) { if (ema.DBCode == dbCode) { return(true); } else { return(false); } } else { return(false); } }
/// <summary> /// 获取某个枚举类型的映射集合 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static List <EnumMappingAttribute> GetMappingList <T>() { List <EnumMappingAttribute> list = new List <EnumMappingAttribute>(); try { Type t = typeof(T); foreach (var fi in t.GetFields(BindingFlags.Static | BindingFlags.Public)) { EnumMappingAttribute spa = Attribute.GetCustomAttributes(fi, typeof(EnumMappingAttribute), true)[0] as EnumMappingAttribute; if (spa != null) { list.Add(spa); } } } catch { list.Clear(); } return(list); }