/*-------------------------------------------------------------------------------------------
* 枚举-字符串 相互转换类
* 创建:杨斌 2011-11-21
* ----------------------------------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GeneralLib
{
///
/// 枚举-字符串 相互转换类
///
/// 枚举类型
public class EnumName
{
private static Dictionary DicNameEnum = null;
///
/// 枚举转字符串名称时的前缀
///
public static string NamePrevStr = "";
///
/// 字符串名称转枚举时,是否忽略大小写
///
public static bool IgnoreCase = true;
///
/// 枚举->字符串
///
///
///
public static string GetName(T type)
{
return NamePrevStr + type.ToString();
}
///
/// 字符串->枚举
///
///
///
public static T GetEnum(string strName)
{
T res = default(T);
if (DicNameEnum == null)
{
DicNameEnum = new Dictionary();
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);
// }
//}
}
}