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

C# 索引器深度解析:語法、多載、介面應用與最佳實務

     編輯:關於C語言

什麼是索引器?

索引器是特殊的屬性,讓類別實例支援陣列語法 obj[index]。它使用 this 關鍵字而非名稱,參數置於方括號內。適用於集合類別、大型資料存取、資源封裝等場景。

基本語法與唯讀/讀寫

class Sample
{
    // 唯讀索引器
    public string this[int index]
    {
        get => $"You passed {index}";
    }

    // 讀寫索引器
    private string[] data = new string[10];
    public string this[int index]
    {
        get => data[index];
        set => data[index] = value;
    }
}

// 使用
var s = new Sample();
Console.WriteLine(s[55]); // 呼叫 get
s[0] = "Hello";           // 呼叫 set

索引器 vs 屬性

特性屬性索引器
識別方式唯一名稱唯一簽章(參數型別/個數),支援多載
靜態性可為 static必須為實例成員
存取子參數無參數可存取索引參數

多參數與多載索引器

參數型別不限於 int,可為 string、enum 等,並支援多參數:

public class Matrix
{
    private double[,] data = new double[10, 10];

    // 兩個整數參數
    public double this[int row, int col]
    {
        get => data[row, col];
        set => data[row, col] = value;
    }

    // 字串參數:依名稱查找
    public double this[string name]
    {
        get => name switch { "trace" => Trace(), _ => 0 };
    }

    private double Trace() { /* ... */ return 0; }
}

介面中宣告索引器

介面只宣告存取子,不加存取修飾詞:

interface IStringIndexer
{
    string this[int index] { get; set; }
}

class MyClass : IStringIndexer
{
    private string[] arr = new string[100];
    public string this[int index]
    {
        get => arr[index];
        set => arr[index] = value;
    }
}

IList<T>、IDictionary<TKey, TValue> 皆定義索引器,統一集合存取介面。

實作建議

  1. 邊界檢查:get/set 內部驗證索引合法性,越界拋 IndexOutOfRangeException 或回傳預設值(依語意)。
  2. 效能:索引器編譯為 get_Item/set_Item 方法,內聯後開銷極低。
  3. 語意清晰:僅當「陣列式存取」符合領域語意時使用;否則用具名方法(GetById、Add)更明確。
  4. 避免副作用:get 不應修改狀態;set 應盡量單一職責。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved