C#获取枚举描述代码

public class MusterEnum
    {
        /// 获取枚举的描述信息
        /// </summary>
        /// <param name="e">传入枚举对象</param>
        /// <returns>得到对应描述信息</returns>
        public String GetEnumDesc(Enum e)
        {
            FieldInfo EnumInfo = e.GetType().GetField(e.ToString());
            if (EnumInfo == null)
            {
                return "";
            }
            DescriptionAttribute[] EnumAttributes
                = (DescriptionAttribute[])EnumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (EnumAttributes.Length > 0)
            {
                return EnumAttributes[0].Description;
            }
            return e.ToString();
        }

        /// <summary>
        /// 将含有描述信息的枚举绑定到列表控件中
        /// </summary>
        /// <param name="listControl"></param>
        /// <param name="enumType"></param>
        private Dictionary<string, string> BindDesEnumToListControl(System.Type enumType)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (object enumValue in Enum.GetValues(enumType))
            {
                Enum e = (Enum)enumValue;
                dic.Add(((int)enumValue).ToString(), GetEnumDesc(e));
            }
            return dic;
        }
}

还有一个是根据传入的枚举的数字索引直接获取

        public static string GetEnumDesc<T>(Object obj)
        {
            obj = (T)obj;
            if (obj == null) throw new ArgumentNullException("参数不能为null");
            if (!obj.GetType().IsEnum) throw new Exception("参数类型不正确");
            FieldInfo fieldinfo = obj.GetType().GetField(obj.ToString());

            string str = string.Empty;
            Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (objs != null && objs.Length != 0)
            {
                DescriptionAttribute des = (DescriptionAttribute)objs[0];
                str = des.Description;
            }
            return str;
        }

 

posted @ 2013-01-28 11:27  屌丝大叔的笔记  阅读(319)  评论(0编辑  收藏  举报