zoukankan      html  css  js  c++  java
  • CLR via C#(18)——Enum

    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);
                }

    image

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

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

    image

    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();

          }

    image

  • 相关阅读:
    又玩起了“数独”
    WebService应用:音乐站图片上传
    大家都来DIY自己的Blog啦
    CSS导圆角,不过这个代码没有怎么看懂,与一般的HTML是不同
    网站PR值
    CommunityServer2.0何去何从?
    网络最经典命令行
    炎热八月,小心"落雪"
    Topology activation failed. Each partition must have at least one index component from the previous topology in the new topology, in the same host.
    SharePoint 2013服务器场设计的一些链接
  • 原文地址:https://www.cnblogs.com/changrulin/p/4778647.html
Copyright © 2011-2022 走看看