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

C# 索引器完整指南:讓物件像陣列一樣存取

     編輯:關於C語言

什麼是索引器?

索引器讓類別的實例可以使用陣列語法 [] 來存取內部資料。它類似屬性,但不需要名稱,改用 this 關鍵字,並接受索引參數。簡單說,索引器讓物件「看起來像陣列」。

語法結構

public 回傳型別 this[參數型別 索引名稱]
{
    get
    {
        // 根據索引回傳值
        return 某個值;
    }
    set
    {
        // 根據索引與 value 設定內部資料
    }
}

完整範例:拼字清單

以下 SpellingList 類別內部用字串陣列儲存單字,透過索引器對外暴露:

using System;

public class SpellingList
{
    protected string[] words = new string[size];
    static public int size = 10;

    public SpellingList()
    {
        for (int x = 0; x < size; x++)
            words[x] = String.Format("Word{0}", x);
    }

    public string this[int index]
    {
        get
        {
            string tmp;
            if (index >= 0 && index <= size - 1)
                tmp = words[index];
            else
                tmp = "";
            return tmp;
        }
        set
        {
            if (index >= 0 && index <= size - 1)
                words[index] = value;
        }
    }
}

public class TestApp
{
    public static void Main()
    {
        SpellingList myList = new SpellingList();

        myList[3] = "=====";
        myList[4] = "Brad";
        myList[5] = "was";
        myList[6] = "Here!";
        myList[7] = "=====";

        for (int x = 0; x < SpellingList.size; x++)
            Console.WriteLine(myList[x]);
    }
}

執行結果

Word0
Word1
Word2
=====
Brad
was
Here!
=====
Word8
Word9

關鍵觀念解析

  • 建構子初始化:第 11-15 行在建構時填入預設值 Word0~Word9。
  • 索引器定義:第 17 行 public string this[int index] 宣告索引器,回傳 string。
  • get 區塊:檢查索引合法性,越界回傳空字串;合法則回傳陣列元素。
  • set 區塊:同樣檢查索引,合法才寫入 value。
  • 用戶端程式碼:myList[3] = "=====" 直接呼叫 set;Console.WriteLine(myList[x]) 呼叫 get。

何時使用索引器?

當它能讓程式碼更易讀、更直觀時。例如實作堆疊、佇列、自訂集合,或封裝大型檔案、有限資源的存取邏輯。避免濫用:若語意不明確,寧可用具名方法。

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