C# for Unity编程语言快速入门教程(连载14)_C#枚举类型



  C#的枚举类型(用 “enum”关键字标识),按照笔者理解本质上是一个隐式继承了System.Enum的×××类。枚举类型的主要作用是:为了更好的识别一个变量的具体含义,且固定变量的使用“范围”。

例如:形如如下定义

public enum Week
{
  Monday,
  Tuesday,
  Wenesday,
  Thursday,
  Friday,
  Saterday,
  Sunday
 }
    
  如果我们没有枚举类型,如何准确表示一个“星期”的概念呢,估计可以用int 或者string 来表示,
但是这种表示,很容易写错以及“越界”。所以枚举类型通常表示哪些必须在一定有限范围内,且有
明确意义的定义。

以下给出部分演示代码,供大家学习参考:


    public enum Week
    {
        Monday = 1,
        Tuesday,
        Wenesday,
        abc,
        Thursday,
        Friday,
        Saterday,
        Sunday
    }

    class Program
    {
        public void Test1()
        {
            Week w = Week.Tuesday;
            Console.WriteLine(w);

            switch (w)
            {
                case Week.Monday:
                    Console.WriteLine("周一");
                    break;
                case Week.Tuesday:
                    Console.WriteLine("周二");
                    break;
                case Week.Wenesday:
                    Console.WriteLine("周三");
                    break;
                case Week.Thursday:
                    break;
                case Week.Friday:
                    break;
                case Week.Saterday:
                    break;
                case Week.Sunday:
                    break;
                default:
                    break;
            }


        }

        ///


        /// 枚举转数值
        ///

        public void Test2()
        {
            Week w = Week.Sunday;
            Console.WriteLine(Convert.ToInt32(w));//输出枚举的“代号”
        }

        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.Test2();
        }
    }