C# 获取枚举的 键姓名,值 和描述 遍历枚举

C# 获取枚举的 键名称,值 和描述 遍历枚举

C# Enum  枚举的操作。  键名称,值 和描述  和 遍历枚举


 /// <summary>

     /// 促销
     /// </summary>
     public enum cxsd
     {




         [Description("推荐")]
         tj = 2,
         [Description("置顶")]
         zd = 4,
         [Description("热卖")]
         rm = 8

     }


//获取 枚举 值

Array rolearry = Enum.GetValues(typeof(cxsd));


//获取枚举名称

String[]rolearry = Enum.GetNames(typeof(cxsd));

获取枚举描述

descriptions(cxsd.rm);//调用

    public static string description(Enum  en)
        {


            Type type = en.GetType();
            MemberInfo[] memInfo = type.GetMember(en.ToString());
            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
                if (attrs != null && attrs.Length > 0)
                    return ((DescriptionAttribute)attrs[0]).Description;
            }
            return en.ToString();
        }

//遍历枚举


  Type type = typeof(cxsd);


            foreach (FieldInfo x in type.GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                cxsd item = (cxsd)x.GetValue(null);
            }

//通过以上方法 扩展一个 通用方法 。来获取  指定值的 描述信息


//调用方法

List<int> vlist=new List<int>();

vlist.add(4);

vlist.add(8);


descriptions<cxsd>(vlist);


 /// <summary>
       /// 获取描述信息
       /// </summary>
       /// <param name="envalue">枚举值的集合</param>
       /// <returns>枚举值对应的描述集合</returns>
       public static List<String> descriptions<T>(List<int> envalue)
       {


           Type type = typeof(T);


                List<String> deslist = new List<String>();


            foreach (FieldInfo x in type.GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                T item = (T)x.GetValue(null);
                if (envalue.Find((int e) => { return e == Convert.ToInt32(item); }) > 0)
                { 
                    deslist.Add(description<T>(item)); 
                }
            }

            return deslist;
       }


         public static string description<T>(T en)
        {


            Type type = en.GetType();
            MemberInfo[] memInfo = type.GetMember(en.ToString());
            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
                if (attrs != null && attrs.Length > 0)
                    return ((DescriptionAttribute)attrs[0]).Description;
            }
            return en.ToString();
        }