首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 建立索引器完整實作教學(二)

     編輯:關於C語言

Employee 類別完整定義

建立包含完整屬性封裝的員工實體類別:

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
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved