C#枚举描述获取

 public static class EnumExtension
    {
        public static string GetDescription(this Enum value)
        {
            FieldInfo field = value.GetType().GetField(value.ToString());
            DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;

            return attribute == null ? value.ToString() : attribute.Description;
        }

        //public static IEnumerable<EnumItem> GetDictionary<TEnum>(this TEnum tEnum)
        //    where TEnum : struct
        //{
        //    return Enum.GetValues(typeof(TEnum)).OfType<Enum>()
        //        .Select(x => new EnumItem
        //        {
        //            Key = Convert.ToInt32(x),
        //            Value = x.ToString(),
        //            Description = x.GetDescription()
        //        });
        //}

        public static IEnumerable<EnumItem> GetDictionary(Type tEnum)
        {
            return Enum.GetValues(tEnum).OfType<Enum>()
                .Select(x => new EnumItem
                {
                    Key = Convert.ToInt32(x),
                    Value = x.ToString(),
                    Description = x.GetDescription()
                });
        }
    }

posted @ 2016-09-05 19:51  GUOKUN  阅读(3119)  评论(0编辑  收藏  举报