在這個案例中,我們將使用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)來解決實際應用問題。