C# 枚举的获取方法

来源:互联网 发布:淘宝手机助手在哪里 编辑:程序博客网 时间:2024/05/22 00:23
  1. 一、Enum的定义 
  2. public enum UserRolesType 
  3. {
  4.   UnKnown=0,
  5.   BaseSimple=70,
  6.   BaseBasic=71,
  7.   
  8.   BaseExtend=72,
  9.   BaseBasic2=88,
  10.   BaseSimple2=89,
  11.   BaseExtend2=90
  12. }
  13. 方法一:根据ID获取枚举对象 
  14.  protected UserRolesType GetEnum(int t)
  15. {
  16.     bool isInEnum = false;
  17.     UserRolesType c = UserRolesType.UnKnown;
  18.     if (t > 0)
  19.     { 
  20.          foreach(int i in Enum.GetValues(typeof(UserRolesType)))
  21.          {
  22.                if (i == t){//this.Debug(t.ToString(), "");
  23.                    c =(UserRolesType)Enum.Parse(typeof(UserRolesType),i.ToString());
  24.                    isInEnum = true;return c;
  25.                    //(Colors)Enum.Parse(typeof(Colors), "Red, Yellow");
  26.           }
  27.      }
  28. if (isInEnum == false)
  29. {
  30.      return UserRolesType.UnKnown;
  31. }
  32. return c; 
  33. }
  34. 方法二:根据ID获取枚举名称
  35. protected string GetEnumName(int s)
  36. {
  37. string str=Enum.GetName(typeof(UserRolesType), s);
  38. if (str == null)
  39. {
  40. str = UserRolesType.UnKnown.ToString();
  41. }
  42. return str;
  43. }
原创粉丝点击