们将使用C#的Dictionary
集合(它是一个键值对集合,类似于其他编程语言中的Map)来存储员工的ID和他们的薪水。我们将创建一个简单的控制台应用程序,用于添加员工、显示员工薪水以及更新员工薪水。
首先,我们需要创建一个Employee
类来存储员工的信息:
public class Employee { public int Id { get; set; } public string Name { get; set; } public decimal Salary { get; set; } }
接下来,我们将创建一个EmployeeManager
类来处理员工的添加、显示和更新操作:
using System; using System.Collections.Generic; public class EmployeeManager { private Dictionary<int, Employee> _employees = new Dictionary<int, Employee>(); public void AddEmployee(Employee employee) { if (!_employees.ContainsKey(employee.Id)) { _employees.Add(employee.Id, employee); } else { Console.WriteLine("Employee with this ID already exists."); } } public void DisplayEmployeeSalary(int employeeId) { if (_employees.ContainsKey(employeeId)) { Employee employee = _employees[employeeId]; Console.WriteLine($"Employee {employee.Name} has a salary of {employee.Salary}."); } else { Console.WriteLine("Employee not found."); } } public void UpdateEmployeeSalary(int employeeId, decimal newSalary) { if (_employees.ContainsKey(employeeId)) { Employee employee = _employees[employeeId]; employee.Salary = newSalary; Console.WriteLine($"Employee {employee.Name}'s salary has been updated to {employee.Salary}."); } else { Console.WriteLine("Employee not found."); } } }
最后,我们将在Main
方法中使用EmployeeManager
类来处理用户输入:
using System; class Program { static void Main(string[] args) { EmployeeManager manager = new EmployeeManager(); while (true) { Console.WriteLine("1. Add Employee"); Console.WriteLine("2. Display Employee Salary"); Console.WriteLine("3. Update Employee Salary"); Console.WriteLine("4. Exit"); Console.Write("Enter your choice: "); int choice = Convert.ToInt32(Console.ReadLine()); switch (choice) { case 1: Console.Write("Enter employee ID: "); int id = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter employee name: "); string name = Console.ReadLine(); Console.Write("Enter employee salary: "); decimal salary = Convert.ToDecimal(Console.ReadLine()); Employee employee = new Employee { Id = id, Name = name, Salary = salary }; manager.AddEmployee(employee); break; case 2: Console.Write("Enter employee ID: "); int displayId = Convert.ToInt32(Console.ReadLine()); manager.DisplayEmployeeSalary(displayId); break; case 3: Console.Write("Enter employee ID: "); int updateId = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter new salary: "); decimal newSalary = Convert.ToDecimal(Console.ReadLine()); manager.UpdateEmployeeSalary(updateId, newSalary); break; case 4: Environment.Exit(0); break; default: Console.WriteLine("Invalid choice. Please try again."); break; } } } }
现在,当你运行这个程序时,你可以添加员工、显示员工薪水以及更新员工薪水。这个简单的例子展示了如何使用C#的Dictionary
集合(类似于其他编程语言中的Map)来解决实际应用问题。