.net c# 获取枚举值集合与其属性


 问题描述:

如下图所示,文章位置是枚举值,生成右边的下拉框。

 

最终选择解决方案:

使用如下方法可以把需要的枚举属性生成字典然后再使用。

 public static Dictionary<int, string> EnumToDictionary<T>()
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            if (!typeof(T).IsEnum)
            {
                return dic;
            }
            string desc = string.Empty;
            foreach (var item in Enum.GetValues(typeof(T)))
            {
                var attrs = item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (attrs != null && attrs.Length > 0)
                {
                    DescriptionAttribute descAttr = attrs[0] as DescriptionAttribute;
                    desc = descAttr.Description;
                }
                dic.Add(Convert.ToInt32(item), desc);
            }
            return dic;
        }

我所使用场景:

 

 舍弃的解决方案:

  public static List<T> EnumToList<T>()
        {
            List<T> list = new List<T>();
            foreach (var item in Enum.GetValues(typeof(T)))
            {
                list.Add((T)item);
            }
            return list;
        }

此种方案生成的结果如下图:

很显然不符合项目要求,故舍弃。

最后附上一个我常用的获取枚举值的描述特性信息的方法:

       public static string GetDescription(this Enum obj)
        {
            return GetDescription(obj, false);
        }
        private static string GetDescription(this Enum obj, bool isTop)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            try
            {
                Type _enumType = obj.GetType();
                DescriptionAttribute dna = null;
                if (isTop)
                {
                    dna = (DescriptionAttribute)Attribute.GetCustomAttribute(_enumType, typeof(DescriptionAttribute));
                }
                else
                {
                    FieldInfo fi = _enumType.GetField(Enum.GetName(_enumType, obj));

                    dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
                }
                if (dna != null && string.IsNullOrEmpty(dna.Description) == false)
                    return dna.Description;
            }
            catch
            {
                return string.Empty;
            }
            return obj.ToString();
        }

该方法使用场景:枚举类型值直接调用-->因为是枚举的扩展方法! 

PS:如果以上有任何错误望各位大牛不吝赐教,同时如果有更好的方法来实现望各位多多留言,互相探讨学习。

【参考文章】http://blog.csdn.net/razorluo/article/details/42707331

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM