C#控制台程序中如何正确显示用户列表的具体信息?
解决用户列表显示类名而非详情的问题
当前程序打印用户列表时输出ElMaestro.User,是因为直接输出User对象时,默认调用Object.ToString()方法,该方法返回类的完全限定名。以下是两种可行的修改方案:
方案一:重写User类的ToString()方法
在User类中添加ToString()的重写逻辑,自定义用户信息的输出格式,这样原有的打印逻辑无需修改即可输出详情。
修改后的User类代码:
namespace ElMaestro { internal class User { private string name; private int score; private string course; public User(string name, int score, string course) { this.name = name; this.score = score; this.course = course; } public void display() { Console.WriteLine("Nombre: " + name); Console.WriteLine("Puntaje del curso: " + score); Console.WriteLine("Estado del curso: " + course); } public string getName() { return name; } // 重写ToString方法,自定义输出格式 public override string ToString() { return $"姓名: {name}, 分数: {score}, 课程状态: {course}"; } } }
方案二:修改UserAdd的printList方法,调用User的display()
利用User类已有的display()方法,在遍历用户列表时直接调用该方法打印详情。
修改后的UserAdd类printList方法:
public void printList() { Console.WriteLine("There are " + list.Count + " Users "); for(int i = 0; i < list.Count; i++) { Console.WriteLine($"{i + 1} ."); list[i].display(); Console.WriteLine("------------------------"); // 可选,用于分隔不同用户 } }
额外修复:Program类中的变量名错误
在Program类的switch分支中,usuarioAdd.printList();存在笔误,应改为userAdd.printList();(与静态变量名一致),否则会编译失败。修改后代码:
case 2: userAdd.printList(); break;
内容的提问来源于stack exchange,提问作者Bayunas
相关产品推荐
相关产品推荐

