1. Enum定义

枚举类型是经常用的一种“名称/值”的形式,例如:

public enum FeedbackStatus
     {
         New,
         Processing,
         Verify,
         Closed
     }

定义枚举类型之后我们在使用时方便了许多,不用再记着0代表什么状态,1代表什么状态。而且枚举类型时强类型的,在编译时就可以进行类型安全检查。枚举类型是值类型的,它是直接从System.Enum继承的,System.Enum又是继承自System.ValueType。但是枚举类型不可以定义方法、属性或者事件。

2. 常用方法

①Enum.GetUnderlyingType:获取枚举类型实例值的基类。

Console.WriteLine(Enum.GetUnderlyingType(typeof(FeedbackStatus)));//结果System.Int32

ToString() :转换为字符串形式

FeedbackStatus status=FeedbackStatus .New ;
    Console.WriteLine(status.ToString());    //结果New
    Console.WriteLine(status.ToString("G")); //结果New
    Console.WriteLine(status.ToString("D")); //结果0

GetValues:获取枚举类型中定义的所有符号以及对应的值。

FeedbackStatus[] status = (FeedbackStatus[])Enum.GetValues(typeof(FeedbackStatus));
            foreach(FeedbackStatus s in status )
            {
                Console.WriteLine("{0:D}--{0:G}", s);
            }

GetNames:获取枚举类型中定义的所有符号。

string[] arr= Enum.GetNames(typeof(FeedbackStatus));
          foreach (string name in arr)
          {
              Console.WriteLine(name);
          }

Parse, TryParse:将文本类型转换为对应的枚举类型。

FeedbackStatus status = (FeedbackStatus)Enum.Parse(typeof(FeedbackStatus), "New", false);
Enum.TryParse("aaa", false, out status);

IsDefine:判断一个值对于一个枚举类型是否合法。

Console .WriteLine(Enum.IsDefined(typeof(FeedbackStatus),1));    //true
Console.WriteLine(Enum.IsDefined(typeof(FeedbackStatus), "New"));//true
Console.WriteLine(Enum.IsDefined(typeof(FeedbackStatus), "new"));//false,区分大小写
Console.WriteLine(Enum.IsDefined(typeof(FeedbackStatus), "aaa"));//false
Console .WriteLine(Enum.IsDefined(typeof(FeedbackStatus ),5));   //false

3. 扩展方法与枚举

上面提到过枚举中是不允许定义方法和事件的。但是我们可以通过扩展方法变相的为枚举添加方法。

public  static class EnumMethod
{
    public static void Show(this FeedbackStatus status)
    {
        string[] arr = Enum.GetNames(typeof(FeedbackStatus));
        Console.WriteLine("枚举类型列表:");
        foreach (string name in arr)
        {
            Console.WriteLine(name);
        }
    }
}

static void Main(string[] args)
      {
          FeedbackStatus status = FeedbackStatus.Processing;
          status.Show();

}

最新文章

  1. [iOS]技巧集锦:UITableView自定义Cell中的控件无法完全对齐Cell的左边界和右边界
  2. pitch yaw roll是什么
  3. Unity3d:UI面板管理整合进ToLua
  4. WP-Cumulus插件
  5. 慕课编程题JS选项卡切换
  6. python反弹tty shell
  7. Win7下用IIS发布网站
  8. android studio无法更新之解决方案
  9. Win7无法设置背景图片的快速解决办法
  10. 新的一年新的气象 云计算与SOA
  11. java中IO递归写入
  12. ELK-Kibana-01
  13. iOS block和代理的区别
  14. 【BZOJ2186】沙拉公主的困惑(数论)
  15. Django之Model
  16. 通过class改变样式
  17. 对String值不可变的理解以及String类型的引用传递问题
  18. CentOS7安装mongodb
  19. Linux 服务器上快速配置阿里巴巴 OPSX NTP服务
  20. 关于js中的回调函数callback

热门文章

  1. 自动布局之autoresizingMask使用详解(Storyboard&Code)
  2. 使用SQLPlus连接Oracle实例
  3. word20161201
  4. 2016年10月16日--ArrayList集合、特殊集合
  5. 火狐浏览器,关闭ssl v3防护
  6. gjd
  7. xargs命令
  8. int型整数中2进制中含有1的个数。
  9. Shell 脚本 ,, 根据进程号退出 从而关机
  10. 64位win系统上面tomcat6启动不了 window不能再本地计算机启动