DOGNET

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace DogNet.Common
{
    /// <summary>
    /// 枚举类型的服务类
    /// </summary>
    public class EnumTypeService
    {
        /// <summary>
        /// 从枚举类型和它的特性读出并返回一个键值对(枚举值和中文描述)
        /// </summary>
        /// <param name="enumType">Type,该参数的格式为typeof(需要读的枚举类型)</param>
        /// <returns>键值对(枚举值和描述)</returns>
        public static Dictionary<string, string> GetNVCFromEnumValue(Type enumType)
        {
            try
            {
                Dictionary<string, string> nvc = new Dictionary<string, string>();

                Type typeDescription = typeof(DescriptionAttribute);
                FieldInfo[] fields = enumType.GetFields();
                string strText = string.Empty;
                string strValue = string.Empty;
                foreach (FieldInfo field in fields)
                {
                    if (field.FieldType.IsEnum)
                    {
                        strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
                        object[] arr = field.GetCustomAttributes(typeDescription, true);
                        if (arr.Length > 0)
                        {
                            DescriptionAttribute aa = (DescriptionAttribute)arr[0];
                            strText = aa.Description;
                        }
                        else
                        {
                            strText = field.Name;
                        }
                        nvc.Add(strValue, strText);
                    }
                }
                return nvc;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 得到值对应的中文状态描述
        /// </summary>
        /// <param name="intKey">状态值</param>
        /// <returns></returns>
        public static string GetDescriptionByKey(Type enumType,int intKey)
        {
            Dictionary<string, string> list = GetNVCFromEnumValue(enumType);

            string strDes = string.Empty;
            list.TryGetValue(intKey.ToString(), out strDes);
            return strDes;
        }
    }

}
posted on 2010-05-18 12:51  DOGNET  阅读(201)  评论(0编辑  收藏  举报