當前位置:網站首頁>c# 獲取枚舉描述的擴展方法

c# 獲取枚舉描述的擴展方法

2022-05-13 23:11:39駕馭人生

/// <summary>
    /// 枚舉擴展類
    /// </summary>
    public static class EnumExtension
    {
        /// <summary>
        /// 獲取枚舉的描述信息
        /// </summary>
        public static string GetDescription(this Enum em)
        {
            Type type = em.GetType();
            FieldInfo fd = type.GetField(em.ToString());
            if (fd == null)
                return string.Empty;
            object[] attrs = fd.GetCustomAttributes(typeof(DescriptionAttribute), false);
            string name = string.Empty;
            foreach (DescriptionAttribute attr in attrs)
            {
                name = attr.Description;
            }
            return name;
        }

        /// <summary>
        /// 根據枚舉值的list 返回所有的描述
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string Descriptionstr<T>(this List<string> list)
        {
            var des = string.Empty;
            foreach (var value in list)
            {
                des = des + ((Enum)Enum.Parse(typeof(T), value)).GetDescription() + ",";
            }
            return des.TrimEnd(',');
        }

        /// <summary>
        /// 根據枚舉值的list 返回所有的描述
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string Descriptionstr<T>(this List<int> list)
        {
            var des = string.Empty;
            foreach (var value in list)
            {
                des = des + ((Enum)Enum.ToObject(typeof(T), value)).GetDescription() + ",";
            }
            return des.TrimEnd(',');
        }
    }

版權聲明
本文為[駕馭人生]所創,轉載請帶上原文鏈接,感謝
https://cht.chowdera.com/2022/133/202205132304581728.html

隨機推薦