C#添加用户输入到字符串列表后遍历无输出问题咨询
问题原因与解决方案
核心问题
- 你在
AttendenceList方法中新建了一个独立的Students类实例:Students list = new();,这个新实例的students列表是初始化后的空列表,和你之前调用Register()方法添加了学生数据的实例不是同一个对象,遍历空列表自然没有输出。 - 你最初收到的
Cannot implicitly convert type 'void' to 'string'报错原因很简单:List<T>.Add()是无返回值的void方法,不能作为返回值赋值给string类型的返回要求,你后来调整的Register()方法写法是正确的。
修复方法
如果AttendenceList本身是Students类的成员方法,不需要额外新建实例,直接遍历当前类的students列表即可:
public void AttendenceList() { Console.WriteLine("All students attending class today:\r\n"); foreach (var item in students) { Console.WriteLine(item); } }
如果AttendenceList是外部类的方法,要保证你调用Register()和AttendenceList时使用的是同一个Students实例,不要每次操作都新建对象。
额外优化建议
你当前的GetValidName()方法存在死循环风险:Console.ReadLine()是写在while循环外面的,如果用户第一次输入为空,循环会一直打印"Not a valid input."但不会让用户重新输入,优化后的写法参考:
public string GetValidName() { Console.WriteLine("Let's get you registered!"); string input; do { Console.WriteLine("Enter your full name: "); input = Console.ReadLine(); if (string.IsNullOrEmpty(input)) { Console.WriteLine("Not a valid input."); } } while (string.IsNullOrEmpty(input)); return input; }
内容的提问来源于stack exchange,提问作者Shubban478
相关产品推荐
相关产品推荐

