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


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值