索引器讓類別實例像陣列一樣使用 obj[index] 語法存取內部資料,是建立直觀集合類別的關鍵語法糖。本文完整示範從容器類別、資料物件到實際使用的三步驟實作。
using System;
using System.Collections;
public class Employees : IEnumerator
{
private ArrayList _employees;
private int _maxEmployees;
public Employees(int maxEmployees)
{
_maxEmployees = maxEmployees;
_employees = new ArrayList(maxEmployees);
}
// 整數索引器
public Employee this[int index]
{
get
{
if (index < 0 || index >= _employees.Count) return null;
return (Employee)_employees[index];
}
set
{
if (index < 0 || index >= _maxEmployees) return;
_employees.Insert(index, value);
}
}
// 字串索引器(依 SSN 查詢)
public Employee this[string ssn]
{
get
{
foreach (Employee emp in _employees)
if (emp.SSN == ssn) return emp;
return null;
}
}
public int Length => _employees.Count;
// IEnumerator 實作(支援 foreach)
public IEnumerator GetEnumerator() => _employees.GetEnumerator();
public bool MoveNext() => _employees.GetEnumerator().MoveNext();
public void Reset() => _employees.GetEnumerator().Reset();
public object Current => _employees.GetEnumerator().Current;
}
public class Employee
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string SSN { get; set; }
public Employee(string first, string middle, string last, string ssn)
{
FirstName = first; MiddleName = middle; LastName = last; SSN = ssn;
}
}
class IndexerSample
{
static void Main(string[] args)
{
try
{
var employees = new Employees(4);
employees[0] = new Employee("Timothy", "Arthur", "Tucker", "555-555-555");
employees[1] = new Employee("Jackie", "zxh", "Cheung", "555-555-552");
employees[2] = new Employee("John", "JHK", "Kong", "555-555-553");
employees[3] = new Employee("Ken", "KNC", "Chang", "555-555-551");
if (args.Length > 0)
{
string ssn = string.Join("", args);
var emp = employees[ssn];
if (emp != null)
Console.WriteLine($"Name: {emp.FirstName} {emp.LastName}, SSN: {ssn}");
else
Console.WriteLine("Can Not find the record!");
}
else
{
for (int i = 0; i < employees.Length; i++)
{
var e = employees[i];
Console.WriteLine($"Name: {e.FirstName} {e.MiddleName} {e.LastName}, SSN: {e.SSN}");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public T this[int x, int y] 適用於矩陣、棋盤等二維資料。get,適合不可變集合。this 關鍵字定義、不支援 ref/out 參數傳遞。FindBySsn)。ArgumentOutOfRangeException 或回傳 null/預設值,文件化行為。IEnumerable<T> 而非舊版 IEnumerator,獲得型別安全與 LINQ 支援。TryGetValue 模式避免例外狀況控制流程。