索引器讓類別/結構支援陣列語法存取內部資料:
myDepartment[0] = "Fred";
myDepartment[1] = "Barney";
public 回傳型別 this[int index]
{
get { ... }
set { ... }
}
using System;
public class Department
{
private string name;
private const int MAX_EMPLOYEES = 10;
private string[] employees = new string[MAX_EMPLOYEES];
public Department(string deptName) => name = deptName;
public string this[int index]
{
get
{
if (index >= 0 && index < MAX_EMPLOYEES)
return employees[index];
throw new IndexOutOfRangeException();
}
set
{
if (index >= 0 && index < MAX_EMPLOYEES)
employees[index] = value;
else
throw new IndexOutOfRangeException();
}
}
}
using System;
public class SalesDept
{
public static void Main(string[] args)
{
Department sales = new Department("Sales");
sales[0] = "Nikki";
sales[1] = "Becky";
Console.WriteLine("The sales team is {0} and {1}", sales[0], sales[1]);
}
}
索引器讓自訂集合類別擁有直覺的陣列存取體驗。