using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; /// /// 枚举拓展 /// namespace Common { /// /// 枚举拓展 /// public static class EnumExtensions { private static Dictionary> enumCache; private static Dictionary> EnumCache { get { if (enumCache == null) { enumCache = new Dictionary>(); } return enumCache; } set { enumCache = value; } } /// ///根据枚举Name获取枚举value /// /// /// /// public static int GetEnumValue(Type enumType, string enumName) { try { if (!enumType.IsEnum) throw new ArgumentException("enumType必须是枚举类型"); var values = Enum.GetValues(enumType); var ht = new Hashtable(); foreach (var val in values) { ht.Add(Enum.GetName(enumType, val), val); } return (int)ht[enumName]; } catch (Exception e) { throw e; } } /// /// 获得枚举提示文本 /// /// /// public static string GetEnumText(this Enum en) { string enString = string.Empty; if (null == en) return enString; var type = en.GetType(); enString = en.ToString(); if (!EnumCache.ContainsKey(type.FullName)) { var fields = type.GetFields(); Dictionary temp = new Dictionary(); foreach (var item in fields) { var attrs = item.GetCustomAttributes(typeof(EnumTextAttribute), false); if (attrs.Length == 1) { var v = ((EnumTextAttribute)attrs[0]).Value; temp.Add(item.Name, v); } } try { EnumCache.Add(type.FullName, temp); } catch { } } if (EnumCache[type.FullName].ContainsKey(enString)) { return EnumCache[type.FullName][enString]; } return enString; } } /// /// 枚举描述 /// public class EnumTextAttribute : Attribute { /// /// /// /// public EnumTextAttribute(string value) { Value = value; } /// /// /// public string Value { get; set; } } }