EnumName.cs 2.41 KB
/*-------------------------------------------------------------------------------------------
 * 枚举-字符串 相互转换类
 * 创建:杨斌 2011-11-21
 * ----------------------------------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GeneralLib
{
    /// <summary>
    /// 枚举-字符串 相互转换类
    /// </summary>
    /// <typeparam name="T">枚举类型</typeparam>
    public class EnumName<T>
    {
        private static Dictionary<string, T> DicNameEnum = null;

        /// <summary>
        /// 枚举转字符串名称时的前缀
        /// </summary>
        public static string NamePrevStr = "";
        /// <summary>
        /// 字符串名称转枚举时,是否忽略大小写
        /// </summary>
        public static bool IgnoreCase = true;

        /// <summary>
        /// 枚举->字符串
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetName(T type)
        {
            return NamePrevStr + type.ToString();
        }

        /// <summary>
        /// 字符串->枚举
        /// </summary>
        /// <param name="strName"></param>
        /// <returns></returns>
        public static T GetEnum(string strName)
        {
            T res = default(T);

            if (DicNameEnum == null)
            {
                DicNameEnum = new Dictionary<string, T>();
                foreach (T type in Enum.GetValues(typeof(T)))
                {
                    string key = GetName(type);
                    if (IgnoreCase) key = key.ToUpper();
                    DicNameEnum.Add(key, type);
                }
            }

            if (IgnoreCase) strName = strName.ToUpper();
            if (DicNameEnum.ContainsKey(strName))
                res = DicNameEnum[strName];

            //下面的方法太慢,因为try catch
            //strName = strName.Substring(PrevStr.Length);
            //try { res = (T)(Enum.Parse(typeof(T), strName, IgnoreCase)); }
            //catch { res = default(T); }            

            return res;
        }

        //public static T GetEnum(int enumType)
        //{
        //    try
        //    {
        //        return (T)(enumType);
        //    }
        //    catch
        //    {
        //        return default(T);
        //    }
        //}
    }

}