C#枚举描述获取

作者: 编程  发布:2019-11-09

 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()
                });
        }
    }

本文由9159.com发布于编程,转载请注明出处:C#枚举描述获取

关键词:

上一篇:没有了
下一篇:没有了