枚举的意义就在于限制变量取值范围。

当可以确定的几种取值时才可以用。

如果输入一个字符串需要进行判断是否是我们需要的字符串时,则一般需要这样写:

using System;
using System.Collections.Generic;
using System.Text;

namespace 枚举学习
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "Male";
            if (s == "Male")
            {
                Console.WriteLine("");
            }
            else if (s == "Female")
            {
                Console.WriteLine("");
            }
            else if (s == "Unknown")
            {
                Console.WriteLine("未知");
            }
            else
            {
                Console.WriteLine("非法输入");
            }
            Console.ReadKey();
        }
    }
}

但是这样写似乎过于麻烦,这时就可以使用枚举类型简单解决,代码如下:

using System;
using System.Collections.Generic;
using System.Text;

//枚举的意义就在于限制变量取值范围。有几种确定的取值时才可以用。
namespace 枚举学习
{
    enum Gender { Male, Female, Unknown };//枚举类型的声明
    class Program
    {     
        static void Main(string[] args)
        {
            Gender s = Gender.Female;//s变量的取值选项只有三个:Male, Female, Unknown。
            Console.WriteLine(s);//打印结果Female
            Console.ReadKey();
      

        }
    }
}

 

相关文章:

  • 2021-09-03
  • 2022-12-23
  • 2022-12-23
  • 2022-01-20
  • 2021-10-09
  • 2021-10-17
  • 2021-11-28
猜你喜欢
  • 2021-12-14
  • 2021-10-08
  • 2022-02-10
  • 2021-07-22
  • 2022-12-23
  • 2021-12-25
相关资源
相似解决方案