定义一个枚举类型:
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();}
参考: