定义一个枚举类型:

public enum City
{
    北京, 上海, 广州
}

控制台判断:

static void Main(string[] args)
{
    Console.WriteLine("北京" == City.北京.ToString());//枚举转字符串 True
    string str1 = Enum.GetName(typeof(City), 0);//枚举转字符串
    Console.WriteLine(str1);//北京
    string str2 = Enum.GetName(typeof(City), City.北京);//枚举转字符串
    Console.WriteLine(str2);//北京
    bool b1 = City.北京 == 0;//枚举与数值可直接比较,无需转换
    Console.WriteLine(b1);//true
    City city = (City)Enum.Parse(typeof(City), "北京");//字符串转枚举
    bool b2 = city == City.北京;
    Console.WriteLine(b2);//true
    bool b3 = Enum.IsDefined(typeof(City), "深圳");//判断某个字符串是否定义
    Console.WriteLine(b3);//false
    bool b4 = Enum.IsDefined(typeof(City), 2);//判断某个整数被定义是否定义
    Console.WriteLine(b4);//true
    Console.ReadKey();
}

参考:(转)C# Enum,Int,String的互相转换 枚举转换

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-30
  • 2022-12-23
  • 2022-03-11
  • 2021-06-22
  • 2021-12-18
  • 2021-12-15
猜你喜欢
  • 2022-12-23
  • 2021-09-18
  • 2021-07-25
  • 2021-10-25
  • 2022-12-23
  • 2021-09-30
相关资源
相似解决方案