C#根据属性描述获取枚举值,获取枚举的属性描述,字符串转枚举

没有优化,凑合着用吧。需要using System.ComponentModel;


 /// 
 /// 根据属性描述获取枚举值
 /// 
 /// 类型
 /// 属性说明
 /// 枚举值
 public static T GetEnum(string des) where T : struct, IConvertible
 {
         Type type = typeof(T);
         if (!type.IsEnum)
         {
                 return default(T);
         }
         T[] enums = (T[])Enum.GetValues(type);
         T temp;
         if (!Enum.TryParse(des, out temp))
         {
                 temp = default(T);
         }
         for (int i = 0; i < enums.Length; i++)
         {
                 string name = enums[i].ToString();
                 FieldInfo field = type.GetField(name);
                 object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
                 if (objs == null || objs.Length == 0)
                 {
                         continue;
                 }
                 DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
                 string edes = descriptionAttribute.Description;
                 if (des == edes)
                 {
                         temp = enums[i];
                         break;
                 }
         }

         return temp;
 }

字符串转为枚举值:


                //字符串转为枚举
                public static T ToEnum(this string enumName) where T : struct, IConvertible
                {
                        Type type = typeof(T);
                        if (!type.IsEnum)
                        {
                                return default(T);
                        }
                        T temp;
                        if (!Enum.TryParse(enumName, out temp))
                        {
                                temp = default(T);
                        }
                        return temp;
                }

下面是获取枚举的属性描述的代码,来源于https://www.cnblogs.com/TanSea/p/6923743.html


        //获取属性描述
        public static string GetEnumDescription(Enum enumValue)
        {
            string value = enumValue.ToString();
            FieldInfo field = enumValue.GetType().GetField(value);
            object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);    //获取描述属性
            if (objs == null || objs.Length == 0)    //当描述属性没有时,直接返回名称
            {
                return value;
            }

            DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
            return descriptionAttribute.Description;
        }

 

你可能感兴趣的:(个人学习笔记,C#整理,属性描述,获取枚举属性描述,根据名字获取枚举,天蘩笔记,枚举操作)