C#入门:如何通过静态方法与List存储并输出影院选座数据?
解决建议
问题点分析
- 未将用户输入的座位信息存入静态List:Main方法中获取了
SeatsInput,但没有调用对应方法把数据添加到List里,导致List始终为空,输出时无内容。 - 静态方法调用错误:
DisplayStuff是ListTest类的静态方法,必须通过ListTest.DisplayStuff()调用,不能直接写DisplayStuff()。 - 语法错误:Main里的
string SeatsInput = CustomerChooseSeats()缺少分号。 - 方法命名不贴合功能:
DisplayTest实际是添加座位的逻辑,改名成AddSeat更直观。
修正后的完整代码
using System; using System.Collections.Generic; static class SeatManager { // 静态List存储座位信息 static List<string> _seatsList = new List<string>(); // 添加座位到List的方法 public static void AddSeat(string seatInput) { _seatsList.Add(seatInput); } // 输出所有已选座位的方法 public static void DisplayAllSeats() { if (_seatsList.Count == 0) { Console.WriteLine("还未选择任何座位"); return; } Console.WriteLine("您选择的座位是:"); foreach (var seat in _seatsList) { Console.WriteLine($"- {seat}"); } } } static string CustomerChooseSeats() { Console.WriteLine("请选择顾客想要的座位:"); string seatsInput = Console.ReadLine(); return seatsInput; } class Program { static void Main() { // 获取用户输入的座位 string seatsInput = CustomerChooseSeats(); // 将座位添加到静态List SeatManager.AddSeat(seatsInput); // 输出所有已选座位 SeatManager.DisplayAllSeats(); // 可取消注释测试多次添加座位 // string anotherSeat = CustomerChooseSeats(); // SeatManager.AddSeat(anotherSeat); // SeatManager.DisplayAllSeats(); } }
关键修改说明
- 完成数据存入逻辑:在Main中调用
SeatManager.AddSeat(seatsInput),把用户输入的座位信息存入静态List。 - 正确调用静态方法:通过类名
SeatManager调用AddSeat和DisplayAllSeats,符合C#静态成员的调用规则。 - 优化输出体验:增加空列表判断,避免无意义输出;用字符串插值让输出格式更清晰。
- 规范命名:将类和方法名改为贴合功能的名称,提升代码可读性。
内容的提问来源于stack exchange,提问作者liam3457454
相关产品推荐
相关产品推荐

