欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# 枚举转键值对,获取描述等通用方法

程序员文章站 2022-06-12 17:01:50
...
 /// <summary>
        /// 扩展方法,获得枚举的Description
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <param name="nameInstead">当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用</param>
        /// <returns>枚举的Description</returns>
        public static string GetDescription<T>(Object value, String otherDesc = "", Boolean nameInstead = false)
        {
            var type = typeof(T);
            if (!type.IsEnum)
            {
                throw new ArgumentException("该对象不是一个枚举类型!");
            }
            string name = Enum.GetName(type, Convert.ToInt32(value));
            if (name == null)
            {
                return otherDesc;
            }
            FieldInfo field = type.GetField(name);
            DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attribute == null && nameInstead == true)
            {
                return name;
            }
            return attribute == null ? otherDesc : attribute.Description;
        }

        /// <summary>
        /// 把枚举转换为键值对集合
        /// </summary>
        /// <param name="enumType">枚举类型</param>
        /// <param name="getText">获得值得文本</param>
        /// <returns>以枚举值为key,枚举文本为value的键值对集合</returns>
        public static Dictionary<Int32, String> EnumToDictionary<T>(EnumAppendItemType appendType = EnumAppendItemType.None)
        {
            var enumType = typeof(T);
            if (!enumType.IsEnum)
            {
                throw new ArgumentException("传入的参数必须是枚举类型!", "enumType");
            }
            Dictionary<Int32, String> enumDic = new Dictionary<int, string>();
            int appendId = Convert.ToInt16(appendType);
            if (appendType != EnumAppendItemType.None)
            {
                enumDic.Add(-999, GetDescription<EnumAppendItemType>(appendId));
            }

            Array enumValues = Enum.GetValues(enumType);
            foreach (Enum enumValue in enumValues)
            {
                Int32 key = Convert.ToInt32(enumValue);
                String value = GetDescription<T>(key);
                enumDic.Add(key, value);
            }
            return enumDic;
        }     
     public enum EnumAppendItemType
      {
          None = -999,
          [Description("--所有--")]
          All = 1,
          [Description("--请选择--")]
          Select = 2,
      }
      /// 
      /// 访问设备
      /// 
      public enum DeviceType
      {
          [Description("PC")]
          PC=1,
          [Description("移动端")]
          Mobile = 2
      }

使用方法:

EnumToDictionary<DeviceType>(EnumAppendItemType.All)

 

注:枚举名是不能出现空格,()-/等字符