Blame view

SunVoteARSPPT/GeneralLib/EnumName.cs 2.41 KB
20c0108c   wutaian   xx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
  /*-------------------------------------------------------------------------------------------
   * 枚举-字符串 相互转换类
   * 创建:杨斌 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);
          //    }
          //}
      }
  
  }