C#列挙に対する一般的な操作

9476 ワード

操作クラスの列挙:
 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         }