程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# 語言中struct的陷阱

C# 語言中struct的陷阱

編輯:C#入門知識

假設我們要為某大學寫一個工資管理程序。首先是表示員工的 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(

							
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved