假設我們要為某大學寫一個工資管理程序。首先是表示員工的 Employee 類(Employee.cs):
01: namespace Skyiv.Ben 02: { 03: class Employee 04: { 05: public string Department { get; private set; } 06: public string Name { get; private set; } 07: public decimal Salary { get; set; } 08: 09: public Employee(string department, string name, decimal salary) 10: { 11: Department = department; 12: Name = name; 13: Salary = salary; 14: } 15: 16: public override string ToString() 17: { 18: return string.Format("{0} {1} 工資:{2:N2}", Department, Name, Salary); 19: } 20: } 21: }
接著是表示學校中各系的 Department 類(Department.cs):
01: namespace Skyiv.Ben 02: { 03: class Department 04: { 05: public string Name { get; private set; } 06: public int Count { get; private set; } 07: public decimal TotalSalary { get; private set; } 08: 09: public Department(string name) 10: { 11: Name = name; 12: } 13: 14: public void Add(Employee employee) 15: { 16: Count++; 17: TotalSalary += employee.Salary; 18: } 19: 20: public override string ToString() 21: { 22: return string.Format("{0} 人數:{1} 總工資:{2:N2}", Name, Count, TotalSalary); 23: } 24: } 25: }
最後就是主程序 Program.cs :
01: using System; 02: using System.Collections.Generic; 03: 04: namespace Skyiv.Ben 05: { 06: class Program 07: { 08: static void Main() 09: { 10: new Program().Run(); 11: } 12: 13: void Run() 14: { 15: var employees = InitializeEmployees(); 16: SalaryRaise(employees); 17: Statistic(employees); 18: } 19: 20: List<Employee> InitializeEmployees() 21: { 22: var employees = new List<Employee>(); 23: employees.Add(new Employee("校長室", "高松年", 72767.58m)); 24: employees.Add(new Employee(