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

C# 索引器完整指南:語法、多參數、字串索引與最佳實務

     編輯:關於C#

什麼是索引器?

索引器讓類別實例像陣列一樣用 obj[index] 存取內部資料,語法上以 this 關鍵字定義。

基本宣告語法

public class MyCollection
{
    private int[] data = new int[10];

    public int this[int index]  // 索引器宣告
    {
        get => data[index];
        set => data[index] = value;
    }
}

// 使用
var c = new MyCollection();
c[3] = 99;
int v = c[3]; // 99

索引器特性總表

特性說明
簽名由參數數量與型別決定,不包含回傳型別或參數名
多載同一類別可定義多個索引器,簽名必須不同
參數型別不限於 int,可為 string、enum、多參數等
非變數索引器值非變數,不可 ref/out 傳遞
命名預設名稱 Item,可用 [IndexerName("Custom")] 變更
存取修飾詞get/set 可分別設定 public/private/protected

範例 1:溫度記錄類別(整數索引)

public class TempRecord
{
    private readonly float[] temps = { 56.2f, 56.7f, 56.5f, 56.9f, 58.8f,
                                       61.3f, 65.9f, 62.1f, 59.2f, 57.5f };

    public int Length => temps.Length;

    public float this[int index]
    {
        get
        {
            if (index < 0 || index >= temps.Length)
                throw new ArgumentOutOfRangeException(nameof(index));
            return temps[index];
        }
        set
        {
            if (index < 0 || index >= temps.Length)
                throw new ArgumentOutOfRangeException(nameof(index));
            temps[index] = value;
        }
    }
}

範例 2:星期名稱查詢(字串索引)

public class DayCollection
{
    private readonly string[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

    public int this[string day]
    {
        get
        {
            for (int i = 0; i < days.Length; i++)
                if (days[i].Equals(day, StringComparison.OrdinalIgnoreCase))
                    return i;
            return -1; // 找不到
        }
    }
}

// 使用
var week = new DayCollection();
Console.WriteLine(week["Fri"]);        // 5
Console.WriteLine(week["Made-up"]);    // -1

範例 3:多參數索引器(矩陣存取)

public class Matrix
{
    private readonly double[,] data;
    public Matrix(int rows, int cols) => data = new double[rows, cols];

    public double this[int row, int col]
    {
        get => data[row, col];
        set => data[row, col] = value;
    }
}

可靠設計原則

  1. 參數驗證:在 get/set 內部檢查邊界,拋出 ArgumentOutOfRangeException 或 ArgumentException。
  2. 非對稱存取權:set 通常比 get 更嚴格(如 public get; private set;)。
  3. 文件化例外:XML 註解標註可能拋出的例外型別與條件。
  4. 避免副作用:get 應為純查詢,不修改狀態。

結語

索引器是封裝集合存取的語法糖,善用多載、字串索引與參數驗證,能設計出直觀、安全的 API。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved