C#枚举描述获取_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > C#枚举描述获取

C#枚举描述获取

 2016/9/5 23:52:25  KING_GUOKUN  程序员俱乐部  我要评论(0)
  • 摘要:publicstaticclassEnumExtension{publicstaticstringGetDescription(thisEnumvalue){FieldInfofield=value.GetType().GetField(value.ToString());DescriptionAttributeattribute=Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)
  • 标签: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()
                });
        }
    }

发表评论
用户名: 匿名