C#基础控制台应用问题:数据库必要性与员工管理方法实现
问题解答
Q1:开发C#基础控制台应用是否必须创建数据库?
不需要。基础控制台应用可以完全依赖内存数据结构(比如List<T>)完成数据的增删查操作,无需数据库。只有当你需要持久化存储数据(即关闭程序后数据不丢失)时,才需要考虑引入数据库、文件存储等持久化方案。
Q2:如何实现AddEmployee、RemoveEmployee、FindEmployee方法?
以下是基于你提供的代码修改后的完整实现,同时满足操作后询问是否继续的需求:
namespace UsingLinq { class Employee { public int Id { get; set; } public string Name { get; set; } public string FatherName { get; set; } } class Program { // 改为静态List,让静态方法可以直接访问 static List<Employee> lstEmployees = new List<Employee>(); static void Main() { while (true) { Console.WriteLine("\n=== 员工管理系统 ==="); Console.WriteLine("1. 添加员工"); Console.WriteLine("2. 删除员工"); Console.WriteLine("3. 查询员工"); Console.WriteLine("请输入你的选择: "); // 处理非数字输入的异常 if (!int.TryParse(Console.ReadLine(), out int selected)) { Console.WriteLine("输入无效,请输入数字1-3!"); ContinuePrompt(); continue; } switch (selected) { case 1: AddEmployee(); break; case 2: RemoveEmployee(); break; case 3: FindEmployee(); break; default: Console.WriteLine("无效选择,请输入1-3之间的数字!"); break; } // 操作后询问是否继续 if (!ContinuePrompt()) { Console.WriteLine("程序已退出"); break; } } } static void AddEmployee() { Console.WriteLine("\n=== 添加员工 ==="); Employee emp = new Employee(); Console.Write("请输入员工ID: "); while (!int.TryParse(Console.ReadLine(), out int id)) { Console.Write("ID必须是数字,请重新输入: "); } emp.Id = id; Console.Write("请输入员工姓名: "); emp.Name = Console.ReadLine()?.Trim() ?? ""; Console.Write("请输入员工父亲姓名: "); emp.FatherName = Console.ReadLine()?.Trim() ?? ""; lstEmployees.Add(emp); Console.WriteLine("员工添加成功!"); } static void RemoveEmployee() { Console.WriteLine("\n=== 删除员工 ==="); Console.Write("请输入要删除的员工ID: "); if (!int.TryParse(Console.ReadLine(), out int id)) { Console.WriteLine("输入的ID无效!"); return; } var empToRemove = lstEmployees.FirstOrDefault(e => e.Id == id); if (empToRemove != null) { lstEmployees.Remove(empToRemove); Console.WriteLine($"ID为{id}的员工已删除!"); } else { Console.WriteLine($"未找到ID为{id}的员工!"); } } static void FindEmployee() { Console.WriteLine("\n=== 查询员工 ==="); Console.Write("请输入要查询的员工ID: "); if (!int.TryParse(Console.ReadLine(), out int id)) { Console.WriteLine("输入的ID无效!"); return; } var emp = lstEmployees.FirstOrDefault(e => e.Id == id); if (emp != null) { Console.WriteLine($"员工ID: {emp.Id}"); Console.WriteLine($"员工姓名: {emp.Name}"); Console.WriteLine($"员工父亲姓名: {emp.FatherName}"); } else { Console.WriteLine($"未找到ID为{id}的员工!"); } } // 提取询问继续的逻辑为单独方法 static bool ContinuePrompt() { Console.Write("\n是否继续操作?(y/n): "); string input = Console.ReadLine()?.Trim().ToLower() ?? ""; while (input != "y" && input != "n") { Console.Write("输入无效,请输入y或n: "); input = Console.ReadLine()?.Trim().ToLower() ?? ""; } return input == "y"; } } }
代码说明:
- 将
lstEmployees改为静态列表,解决静态方法无法访问非静态成员的问题 - 添加了输入异常处理,避免用户输入非数字导致程序崩溃
- 实现三个核心方法:
AddEmployee:收集员工信息并添加到列表RemoveEmployee:根据ID查找并删除员工FindEmployee:根据ID查询员工信息并展示
- 新增
ContinuePrompt方法,统一处理操作后的继续/退出逻辑 - 优化控制台输出可读性,添加分隔标题
内容的提问来源于stack exchange,提问作者Asmar J.
相关产品推荐
相关产品推荐

