C#对枚举的常用操作

枚举操作类:

 1  public partial class XEnumHelper
 2     {
 3         /// <summary>
 4         /// 获得枚举的所有枚举项
 5         /// </summary>
 6         /// <param name="enumType"></param>
 7         /// <returns></returns>
 8         public static IList<string> GetEnums(Type enumType)
 9         {
10             IList<string> enums = new List<string>();
11 
12             foreach (string s in Enum.GetNames(enumType))
13             {
14                 enums.Add(s);
15             }
16 
17             return enums;
18         }
19 
20         /// <summary>
21         /// 将字符串转换为枚举
22         /// </summary>
23         /// <param name="enumType">枚举类型</param>
24         /// <param name="strValue">字符串值</param>
25         /// <returns></returns>
26         public static object String2Enum(Type enumType, string strValue)
27         {
28             return Enum.Parse(enumType, strValue);
29         }
30     }

枚举定义:

1 public enum OperateType
2         {
3             None = 0,
4             Add = 1,
5             Edit = 2,
6             Delete = 3
7         }

客户端调用:

 1  static void Main(string[] args)
 2         {
 3             //获取枚举的常数值
 4             OperateType opreateType = OperateType.Edit;
 5             int num = (int)opreateType;
 6             Console.WriteLine("枚举项Edit的常数值为:{0}", num);
 7 
 8             //字符串转换为枚举值
 9             string optType = "Delete";
10             opreateType = (OperateType)XEnumHelper.String2Enum(typeof(OperateType), optType);
11             Console.WriteLine("字符串值:{0}转换为枚举类型:{1}", optType, opreateType);
12 
13             //通过枚举的常数值获得枚举值
14             num = 3;
15             opreateType = (OperateType)num;
16             Console.WriteLine("枚举项常数值为3对应的枚举项为:{0}", opreateType);
17 
18             //列举枚举值
19             IList<string> enums = XEnumHelper.GetEnums(typeof(OperateType));
20             int loopNo = 0;
21             foreach (string e in enums)
22             {
23                 loopNo += 1;
24                 Console.WriteLine("枚举项{0}:{1}", loopNo, e);
25             }
26 
27             Console.Read();
28         }

 

 

posted on 2012-05-06 15:08  武子  阅读(1540)  评论(0)    收藏  举报

导航