建立包含完整屬性封裝的員工實體類別:
public class Employee
{
private string _firstName;
private string _middleName;
private string _lastName;
private string _ssn;
public Employee(string firstName, string middleName, string lastName, string ssn)
{
_firstName = firstName;
_middleName = middleName;
_lastName = lastName;
_ssn = ssn;
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string MiddleName
{
get { return _middleName; }
set { _middleName = value; }
}
public string SSN
{
get { return _ssn; }
set { _ssn = value; }
}
}
此類別可搭配索引器實作集合類別,例如:
public class EmployeeCollection
{
private List<Employee> _employees = new List<Employee>();
public Employee this[int index]
{
get { return _employees[index]; }
set { _employees[index] = value; }
}
public Employee this[string ssn]
{
get { return _employees.Find(e => e.SSN == ssn); }
}
public void Add(Employee emp) => _employees.Add(emp);
}
var coll = new EmployeeCollection();
coll.Add(new Employee("John", "A.", "Doe", "123-45-6789"));
coll.Add(new Employee("Jane", "B.", "Smith", "987-65-4321"));
Console.WriteLine(coll[0].FirstName); // John
Console.WriteLine(coll["987-65-4321"].FirstName); // Jane