QQstate state = QQstate.Online; // 枚举类型默认可与int类型互相转换 枚举类型和int类型是兼容的 // 通过强制转换进行转换 // 枚举类型转int类型 int n = (int)state; Console.WriteLine(n); // #region可以将写好的一个模块隐藏起来,清晰界面 #region 写了一个5,并显示 int number = 5; Console.WriteLine(number); #endregion // int类型转枚举类型 int n2 = 3; Season season = (Season)n2; Console.WriteLine(season); // 所有的类型都能转换为string类型 int n3 = 10; string s = n3.ToString(); decimal d = 5000m; string s2 = d.ToString(); Console.WriteLine(s); Console.WriteLine(d); // 枚举与字符串的转换 QQstate state2 = QQstate.QMe; string s3 = state2.ToString(); Console.WriteLine(s3); // 字符串转换为枚举 string s4 = "3"; //or string s4="Winter"; //调用parse帮助我们将字符串转换为对应的枚举类型; // Season season2= (Season)Enum.Parse(typeof(Season), s4); Console.WriteLine(season2); public enum QQstate { //枚举的int类型默认从0开始; Online, Basy, Offline, Leave, QMe } public enum Season { //在这个枚举中的默认转换则从4开始 Spring=3, Summer, Autumn, Winter }
//用户输入数字,程序显示对应状态 #region 第一种方法 bool b = true; while (b) { Console.WriteLine("请输入您的QQ状态:1-Online;2-Offline;3-basy;4-leave;5-QMe"); string State = Console.ReadLine(); switch (State) { case "1": QQstate state = (QQstate)Enum.Parse(typeof(QQstate), State); Console.WriteLine(state); b = false; break; case "2": QQstate state2 = (QQstate)Enum.Parse(typeof(QQstate), State); Console.WriteLine(state2); b = false; break; case "3": QQstate state3 = (QQstate)Enum.Parse(typeof(QQstate), State); Console.WriteLine(state3); b = false; break; case "4": QQstate state4 = (QQstate)Enum.Parse(typeof(QQstate), State); Console.WriteLine(state4); b = false; break; case "5": QQstate state5 = (QQstate)Enum.Parse(typeof(QQstate), State); Console.WriteLine(state5); b = false; break; default: Console.WriteLine("输入有误,请重新输入"); break; } } #endregion // 思考:如果是直接转化的话可以考虑去除switch结构,直接进行转化,并添加try、catch与循环保证程序稳定正常运行 //下面这种方法的漏洞在于输入数字时转化失败并不报错,所以成功的还是上一种 bool bo = true; while (bo) { try { Console.WriteLine("请输入您的QQ状态:1-Online;2-Offline;3-basy;4-leave;5-QMe"); string State_levelup = Console.ReadLine(); QQstate state_levelup = (QQstate)Enum.Parse(typeof(QQstate), State_levelup); Console.WriteLine(state_levelup); bo = false; } catch { Console.WriteLine("输入有误请重新输入"); } } public enum QQstate { Online=1, Offline, Basy, Leave, QMe }