索引子 (C# 程式設計手冊)

索引子 (Indexer) 允許使用與陣列相同的方式來索引類別 (Class) 或結構 (Struct) 的執行個體。 索引子除了其存取子 (Accessor) 會使用參數以外,其餘特性都與屬性相似。

在下列範例中,將定義一個泛型類別,並提供簡單的 getset 存取子方法來做為指派與擷取值的方式。 Program 類別會建立此類別的執行個體以儲存字串。

class SampleCollection<T>
{
    // Declare an array to store the data elements.
    private T[] arr = new T[100];

    // Define the indexer, which will allow client code
    // to use [] notation on the class instance itself.
    // (See line 2 of code in Main below.)        
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets
            // the corresponding element from the internal array.
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer.
class Program
{
    static void Main(string[] args)
    {
        // Declare an instance of the SampleCollection type.
        SampleCollection<string> stringCollection = new SampleCollection<string>();

        // Use [] notation on the type.
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}

索引子概觀

  • 索引子可讓物件以類似於陣列的方式進行索引。

  • get 存取子會傳回一個值。 set 存取子會指定一個值。

  • this 關鍵字的用途為定義索引子。

  • value 關鍵字是用來定義 set 索引子所指定的值。

  • 索引子不需要以整數值來索引;您可以決定如何定義特定的查詢機制。

  • 索引子可以多載。

  • 索引子可以具有一個以上的型式參數,例如,在存取二維陣列時便是如此。

相關章節

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格。 語言規格是 C# 語法和用法的決定性來源。

請參閱

參考

屬性 (C# 程式設計手冊)

概念

C# 程式設計手冊