1. 程式人生 > 實用技巧 >列舉轉換成字典集合的通用方法

列舉轉換成字典集合的通用方法

列舉轉換成字典集合的通用方法(https://www.cnblogs.com/eggTwo/p/5950131.html)

1.這裡我就直接列舉程式碼如下:

 public static class EnumHelper
    {
        /// <summary>
        /// 根據列舉的值獲取列舉名稱
        /// </summary>
        /// <typeparam name="T">列舉型別</typeparam>
        /// <param name="status">列舉的值</param>
        /// <returns></returns>
        public static string GetEnumName<T>(this int status)
        {
            return Enum.GetName(typeof(T), status);
        }
        /// <summary>
        /// 獲取列舉名稱集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static string[] GetNamesArr<T>()
        {
            return Enum.GetNames(typeof(T));
        }
        /// <summary>
        /// 將列舉轉換成字典集合
        /// </summary>
        /// <typeparam name="T">列舉型別</typeparam>
        /// <returns></returns>
        public static Dictionary<string, int> getEnumDic<T>()
        {

            Dictionary<string, int> resultList = new Dictionary<string, int>();
            Type type = typeof(T);
            var strList = GetNamesArr<T>().ToList();
            foreach (string key in strList)
            {
                string val = Enum.Format(type, Enum.Parse(type, key), "d");
                resultList.Add(key, int.Parse(val));
            }
            return resultList;
        }
        /// <summary>
        /// 將列舉轉換成字典
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <returns></returns>
        public static Dictionary<string, int> GetDic<TEnum>()
        {
            Dictionary<string, int> dic = new Dictionary<string, int>();
            Type t = typeof(TEnum);
            var arr = Enum.GetValues(t);
            foreach (var item in arr)
            {
                dic.Add(item.ToString(), (int)item);
            }

            return dic;
        }

    }
  public enum Sex
    {
        man,
        woman
    }
    public enum Color
    {
        red,
        blue
    }

使用方法如下:

 static void Main(string[] args)
        {
            var name = EnumHelper.GetEnumName<Sex>(1);
            Console.WriteLine("數字轉字串:"+name);
            var dic1 = EnumHelper.getEnumDic<Sex>();
            Console.WriteLine("列舉轉字典集合方法1:");
            foreach (var item in dic1)
            {
                Console.WriteLine(item.Key + "==" + item.Value);
            }
            Console.WriteLine("列舉轉字典集合方法2:");
            var dic= EnumHelper.GetDic<Color>();
            foreach (var item in dic)
            {
                Console.WriteLine(item.Key+"=="+item.Value);
            }
            Console.ReadLine();
        }