C#枚舉擴展方法,獲取枚舉值的描述值以及獲取一個枚舉類下面所有的元素
阿新 • • 發佈:2017-08-01
cache dict logs int info 擴展方法 attrs format 獲取
/// <summary> /// 枚舉擴展方法 /// </summary> public static class EnumExtension { private static Dictionary<string, Dictionary<string, string>> _enumCache; /// <summary> /// 緩存 /// </summary> private static Dictionary<string, Dictionary<string, string>> EnumCache { get { return _enumCache ?? (_enumCache = new Dictionary<string, Dictionary<string, string>>()); } set { _enumCache = value; } } /// <summary> /// 獲取枚舉描述信息 /// </summary> /// <param name="en"></param>/// <returns></returns> public static string GetEnumText(this System.Enum en) { string enString = string.Empty; if (null == en) return enString; Type type = en.GetType(); enString = en.ToString(); if (!EnumCache.ContainsKey(type.FullName)) { System.Reflection.FieldInfo[] fields= type.GetFields(); Dictionary<string, string> temp = new Dictionary<string, string>(); foreach (FieldInfo item in fields) { object[] attrs = item.GetCustomAttributes(typeof(TextAttribute), false); if (attrs.Length == 1) { string v = ((TextAttribute)attrs[0]).Value; temp.Add(item.Name, v); } } EnumCache.Add(type.FullName, temp); } if (EnumCache[type.FullName].ContainsKey(enString)) { return EnumCache[type.FullName][enString]; } return enString; } /// <summary> /// 遍歷枚舉對象的所有元素 /// </summary> /// <typeparam name="T">枚舉對象</typeparam> /// <returns>Dictionary:枚舉值-描述</returns> public static Dictionary<int, string> GetEnumValues<T>() { Dictionary<int, string> dictionary = new Dictionary<int, string>(); foreach (var code in System.Enum.GetValues(typeof(T))) { ////獲取名稱 //string strName = System.Enum.GetName(typeof(T), code); object[] objAttrs = code.GetType().GetField(code.ToString()).GetCustomAttributes(typeof(TextAttribute), true); if (objAttrs.Length > 0) { TextAttribute descAttr = objAttrs[0] as TextAttribute; if (!dictionary.ContainsKey((int)code)) { if (descAttr != null) dictionary.Add((int)code, descAttr.Value); } //Console.WriteLine(string.Format("[{0}]", descAttr.Value)); } //Console.WriteLine(string.Format("{0}={1}", code.ToString(), Convert.ToInt32(code))); } return dictionary; } } /// <summary> /// 自定義描述 /// </summary> public class TextAttribute : Attribute { public TextAttribute(string value) { Value = value; } /// <summary> /// 描述信息 /// </summary> public string Value { get; set; } }
C#枚舉擴展方法,獲取枚舉值的描述值以及獲取一個枚舉類下面所有的元素