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

.NET 索引器完整指南:語法、特性、重載與實戰模式

     編輯:ASP.NET 基礎

什麼是索引器

索引器讓類或結構體像陣列一樣通過下標訪問內部數據,語法形式為 this[參數列表]。它是「屬性」的參數化泛化,本質是 get/set 訪問器的語法糖。

核心語法結構

public class SampleCollection
{
    private T[] _items = new T[100];

    // 索引器聲明
    public T this[int index]
    {
        get => _items[index];
        set => _items[index] = value;
    }
}

七大核心特性

特性說明示例
語法糖編譯為 get_Item/set_Item 方法IL 可見 get_Item(Int32)
this 關鍵字標識索引器,非實例引用this[int i]
value 隱式參數set 訪問器自動可用set { _arr[i] = value; }
參數靈活可為任意類型、多參數this[string key]、this[int x, int y]
支援重載同類多個索引器,參數簽名不同按 int 索引 / 按 string 鍵 並存
可多維模擬多維陣列/矩陣訪問matrix[x, y]
介面實現介面可聲明索引器,類實現隱式/顯式interface IRepo { T this[string id] { get; } }

進階實戰模式

1. 字符串鍵索引器(字典語義)

public class ConfigStore
{
    private readonly Dictionary _data = new Dictionary();

    public string this[string key]
    {
        get => _data.TryGetValue(key, out var v) ? v : null;
        set => _data[key] = value ?? throw new ArgumentNullException(nameof(value));
    }
    
    // 唯讀索引器(僅 get)
    public string this[string key, bool readOnly]
    {
        get => this[key];
    }
}

2. 多維索引器(矩陣/棋盤)

public class Matrix
{
    private readonly T[,] _grid;
    public int Rows { get; }
    public int Cols { get; }

    public Matrix(int rows, int cols)
    {
        Rows = rows; Cols = cols;
        _grid = new T[rows, cols];
    }

    public T this[int row, int col]
    {
        get
        {
            Validate(row, col);
            return _grid[row, col];
        }
        set
        {
            Validate(row, col);
            _grid[row, col] = value;
        }
    }

    private void Validate(int r, int c)
    {
        if (r < 0 || r >= Rows || c < 0 || c >= Cols)
            throw new IndexOutOfRangeException($"({r},{c}) 超出範圍 [{Rows}x{Cols}]");
    }
}

3. 介面索引器與顯式實現

public interface IRepository
{
    T this[string id] { get; set; }
    IEnumerable All { get; }
}

public class UserRepository : IRepository
{
    private readonly Dictionary _users = new Dictionary();

    // 隱式實現
    public User this[string id]
    {
        get => _users.TryGetValue(id, out var u) ? u : null;
        set => _users[id] = value;
    }

    public IEnumerable All => _users.Values;
}

4. 只讀索引器(C# 6+ 表達式體)

public class ReadOnlyList
{
    private readonly T[] _items;
    public ReadOnlyList(params T[] items) => _items = items;
    
    public T this[int i] => _items[i]; // 僅 get
    public int Count => _items.Length;
}

索引器 vs 屬性 vs 方法

維度屬性索引器方法
參數無有(至少一個)任意
調用語法obj.Propobj[index]obj.Method(arg)
適用場景單一值特徵集合/映射訪問行為/計算/副作用
重載不可可可
介面聲明可可可

最佳實踐與避坑指南

  1. 邊界檢查:get/set 內部務必驗證索引合法性,拋出 IndexOutOfRangeException 或 ArgumentOutOfRangeException
  2. 避免副作用:get 應為純查詢,不修改狀態;複雜計算改用方法
  3. 命名清晰:多參數索引器參數名要有語義 this[int row, int column] 而非 this[int a, int b]
  4. 考慮 TryGet 模式:高頻失敗場景提供 bool TryGet(int index, out T value) 避免異常開銷
  5. 文檔註釋:/// 零基索引 明確語義

經典框架中的索引器應用

  • List<T>[int] — 基礎陣列訪問
  • Dictionary<TKey,TValue>[TKey] — 鍵值映射,set 覆蓋/添加,get 不存在拋異常
  • DataTable.Rows[int] — 行集合訪問返回 DataRow
  • ConfigurationManager.AppSettings[string] — 配置讀取
  • HttpContext.Current.Items[object] — 請求級數據槽

結語

索引器是 .NET 類庫設計中賦予類型「集合語義」的關鍵機制。合理運用重載、多維、介面實現等高級特性,能讓自定義類型擁有如原生陣列、字典般直觀的使用體驗。記住:索引器本質是帶參數的屬性,設計時遵循屬性的純粹性原則。

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