你的位置:首页 > ASP.net教程

[ASP.net教程]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()
                });
        }
    }