Using enums and switch c#
本问题已经有最佳答案,请猛点这里访问。
我在使用带开关的枚举时遇到一些问题,我的任务是输入国家的名称,然后显示世界上哪个地方是那个国家。我不能从键盘上读取枚举。我犯了错误吗?谢谢你的帮助。`
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Program { enum Country{ Spain,USA,Japan }; static void Main(string[] args) { Country country = new Country(); Console.WriteLine("Enter the number of country 1.Spain 2.The USA 3.Japan"); country = Console.ReadLine(); switch (country) { case Country.Spain: Console.WriteLine("Its in Europe"); break; case Country.USA: Console.WriteLine("Its in North America"); break; case Country.Japan: Console.WriteLine("Its in Asia"); break;`enter code here` } Console.ReadKey(); } } |
您需要将字符串格式化为枚举:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | enum Country { Spain, USA, Japan }; static void Main(string[] args) { Country country; Console.WriteLine("Enter the number of country 1.Spain 2.The USA 3.Japan"); string input = Console.ReadLine(); bool sucess = Enum.TryParse<Country>(input, out country); if (!sucess) { Console.WriteLine("entry {0} is not a valid country", input); return; } switch (country) { case Country.Spain: Console.WriteLine("Its in Europe"); break; case Country.USA: Console.WriteLine("Its in North America"); break; case Country.Japan: Console.WriteLine("Its in Asia"); break; } Console.ReadKey(); } |