码迷,mamicode.com
首页 > 其他好文 > 详细

获取根据枚举名称获取枚举描述

时间:2016-05-06 14:40:35      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

     /// <summary>
        /// 获取根据枚举名称获取枚举描述
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="enumName">枚举名称</param>
        /// <returns></returns>
        public static string GetEnumDescription<T>(string enumName){

            string result = string.Empty;
            System.Reflection.FieldInfo field = typeof(T).GetField(enumName);
            if (field != null)
            {
                object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
                if (objs == null || objs.Length == 0)
                    result = enumName;
                else
                {
                    System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0];
                    result = da.Description;
                }
            }
            else { result = enumName; }
            return result;
        }


        /// <summary>
        /// 获取枚举的description
        /// </summary>
        /// <param name="enumSubitem">枚举值</param>
        /// <returns>枚举对应的介绍</returns>
        public static string GetEnumDescription(object enumSubitem)
        {
            enumSubitem = (Enum)enumSubitem;
            string strValue = enumSubitem.ToString();

            FieldInfo fieldinfo = enumSubitem.GetType().GetField(strValue);

            if (fieldinfo != null)
            {

                Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (objs == null || objs.Length == 0)
                {
                    return strValue;
                }
                else
                {
                    DescriptionAttribute da = (DescriptionAttribute)objs[0];
                    return da.Description;
                }
            }
            else
            {
                return "不限";
            }

        }

 

获取根据枚举名称获取枚举描述

标签:

原文地址:http://www.cnblogs.com/songxiii/p/5465515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!