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

C# 索引器完整指南:建立自訂集合存取介面

     編輯:關於C#

前言

索引器讓類別實例像陣列一樣使用 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 參數傳遞。

最佳實踐建議

  1. 索引器邏輯保持簡單,複雜查詢改用方法(如 FindBySsn)。
  2. 引數驗證:越界拋 ArgumentOutOfRangeException 或回傳 null/預設值,文件化行為。
  3. 實作 IEnumerable<T> 而非舊版 IEnumerator,獲得型別安全與 LINQ 支援。
  4. 考慮 TryGetValue 模式避免例外狀況控制流程。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved