C# 图解教程 第 12 章 枚举(笔记+模仿代码)

12.1 枚举

        enum Food
        { 
            Fish,
            Beef,
            Mutton
        }
        static void Main()
        {
            Food food = Food.Beef;
            Console.WriteLine(food);				// Beef
            Console.WriteLine("{0}", food);			// Beef
            Console.WriteLine("{0}", (int)food);	// 1
        }
  • 枚举是值类型;
  • 枚举只有一种类型的成员:命名的整型常量,默认为int类型,默认从 0 开始赋值,每一个后续成员比前一个的值多 1。

12.1.1 设置底层类型和显式值

        enum Food : long	// 设置底层类型为 long
        { 
            Fish,			// 首元素没有显式值,默认为 0
            Beef,			//  0 + 1 = 1
            Mutton = 200,	// 设置显式值
            Fruit			// 200 + 1 = 201
        }

12.2 位标志

        [Flags]	// Flags 特性会通知查看这段代码的工具,提供一些便捷
        enum Settings : short
        { 
            FullScreen      = 0x01,
            EasyMode        = 0x02,
            TwoPlayer       = 0x04,
            Whatever        = 0x08
        }
        class MyClass
        {
            bool UseFullScreen  = false,
                 UseEasyMode    = false,
                 UseTwoPlayer   = false,
                 UseWhatever    = false;
            public void SetOptions(Settings ops)
            {
                UseFullScreen   = ops.HasFlag(Settings.FullScreen);
                UseEasyMode     = ops.HasFlag(Settings.EasyMode);
                UseTwoPlayer    = ops.HasFlag(Settings.TwoPlayer);
                UseWhatever     = ops.HasFlag(Settings.Whatever);
            }
            public void PrintOptions()
            {
                Console.WriteLine($"Option settings:");
                Console.WriteLine($"Use Full Screen         - { UseFullScreen }");
                Console.WriteLine($"Use Easy Mode           - { UseEasyMode }");
                Console.WriteLine($"Use Two Player          - { UseTwoPlayer }");
                Console.WriteLine($"Use Whatever            - { UseWhatever }");
            }
        }
        static void Main()
        {
            MyClass mc = new MyClass();
            Settings ops = Settings.EasyMode | Settings.FullScreen;
            mc.SetOptions(ops);
            mc.PrintOptions();
        }

12.3 关于枚举的更多内容

  • 不能对成员使用修饰符,自动和枚举具有相同的可访问性;
  • 成员是静态的,没有该枚举类型的变量时也可以访问;
  • 只能比较同一枚举类型的成员。
        enum Food : long
        {
            Fish,
            Beef,		
            Mutton = 200,
            Fruit		
        }
        static void Main()
        {
            Console.WriteLine("Third member of Food is {0}, its value is {1}"
                , Enum.GetName(typeof(Food), 200), (int)Food.Mutton);
            foreach (var name in Enum.GetNames(typeof(Food)))
                Console.WriteLine(name);
        }

上面的例子演示了Enum类型的两个静态方法:GetNameGetNames

你可能感兴趣的:(C#,图解教程)