C#中除了简单的变量类型外,还提供了三种较为复杂的变量类型,包括枚举、结构和数组。本文主要讲述枚举相关的知识。

    枚举类型(也称为枚举),提供了一种有效的方式,来定义可能分配给变量的一组已命名整数常量,使用enum关键字声明。

    默认情况下,第一个枚举数的值为0,之后每个连续枚举数的值加1;若设置某一枚举数的值,之后的枚举数仍然按1递增。示例如下:

        enum Day
        {
            Sunday,
            Monday,
            Tuesday,
            Wednesday,
            Thursday,
            Friday,
            Saturday
        };

        enum Number
        {
            One = 1,
            Two,
            Three,
            Eleven = 11,
            Twelve,
            Thirteen
        };    

     枚举中每个元素的基础类型都是int,可以使用冒号指明另一种整数类型。已批准的枚举类型有:byte、sbyte、short、ushort、int、uint、long、ulong

        enum Month : byte
        {
            January,
            February,
            March,
            April,
            May,
            June,
            July,
            August,
            September,
            October,
            November,
            December
        };

    枚举类型的枚举器列表中元素可以分配为任何值,同时也可以使用计算值

        enum MachineState
        {
            PowerOff = 0,
            Running = 5,
            Sleeping = 10,
            Hibernating = Sleeping + 5
        }

      枚举相关的转换:

      1.转换成整数

            Day today = Day.Wednesday;
            Console.WriteLine($"today is {today}");

            int dayNumber = (int)today;
            Console.WriteLine($"{today} is day number {dayNumber}");
   
             Month month = Month.January;
            byte monthNumber = (byte)month;
            Console.WriteLine($"{month} is month number {monthNumber}");

       输出:       

     2.转换成字符串

            string todayString = Convert.ToString(today);
            Console.WriteLine($"Convert.ToString()方式: {todayString}");

            string todayString2 = today.ToString();
            Console.WriteLine($".ToString()方式:{todayString2}");

     输出:    

                         

    3.从字符串中获取枚举值

     Enum.Parse()静态方法,带有3个参数。第一个参数是要使用的枚举类型,其语法是关键字typeof后跟放在括号中的枚举类名;第二个参数是要转换的字符串;第三个参数是一个bool值,指定在进行转换时是否忽略大小写。

            string todayData = "Wednesday";
            Day dayData = (Day)Enum.Parse(typeof(Day), todayData, true);
            Console.WriteLine($"Enum.Parse()方法:{dayData}");

    输出:         

    3个方法: Enum.GetName() 、Enum.GetNames()、Enum.GetValues()

            string name = Enum.GetName(typeof(Day), 3);
            Console.WriteLine(name);

            Console.WriteLine("The names of the Day Enum are:");
            foreach (string str in Enum.GetNames(typeof(Day)))
                Console.Write(str + " ");
            Console.WriteLine();

            Console.WriteLine("The values of the Day Enum are:");
            foreach (int value in Enum.GetValues(typeof(Day)))
                Console.Write(value + " ");
            Console.WriteLine();

   输出:  

                          

     枚举类型作为位标志:定义枚举时,添加Flags特性,之后便可以对这些值执行AND、OR、NOT、XOR按位运算

        [Flags]
        enum WeekDay
        {
            None = 0x00,       //0000 0000
            Sunday = 0x01,     //0000 0001
            Monday = 0x02,     //0000 0010
            Tuesday = 0x04,    //0000 0100
            Wednesday = 0x08,  //0000 1000
            Thursday = 0x10,   //0001 0000
            Friday = 0x20,     //0010 0000
            Saturday = 0x40    //0100 0000
        };

        [Flags]
        public enum CarOptions
        {
            // The flag for SunRoof is 0001.
            SunRoof = 0x01,
            // The flag for Spoiler is 0010.
            Spoiler = 0x02,
            // The flag for FogLights is 0100.
            FogLights = 0x04,
            // The flag for TintedWindows is 1000.
            TintedWindows = 0x08,
        }

   AND(&):判断是否包含该值;OR(|):组合;NOT(~):取反;XOR(^):去除其中一个值

            CarOptions options = CarOptions.SunRoof | CarOptions.FogLights;
            Console.WriteLine(options);
            Console.WriteLine((int)options);

            WeekDay meetingDays = WeekDay.Tuesday | WeekDay.Thursday;
            meetingDays = meetingDays | WeekDay.Friday;
            Console.WriteLine("Meeting days are {0}", meetingDays);

            meetingDays = meetingDays ^ WeekDay.Tuesday;
            Console.WriteLine("Meeting days are {0}", meetingDays);

            bool test = (meetingDays & WeekDay.Thursday) == WeekDay.Thursday;
            Console.WriteLine("Thursday {0} a meeting day.", test == true ? "is" : "is not");

     输出:

        

    注释掉[Flags]后,输出内容为:

                             

参考文章:

https://www.cnblogs.com/williamwsj/p/6047884.html

https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/enum

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/enumeration-types

 

 

posted on 2018-01-31 14:18  雪溪  阅读(15177)  评论(0编辑  收藏  举报