C#類學習-9

C#中類的索引器

索引器允許類或結構的實例

就像數組一樣進行索引。

索引器類似於屬性,不同處在於它們的訪問器採用參數。

索引器概述:

  • 使用索引器可以用類似於數組的方式爲對象建立索引。
  • get 訪問器返回值。set 訪問器分配值。
  • this 關鍵字用於定義索引器。
  • value 關鍵字用於定義由 set 索引器分配的值。
  • 索引器不必根據整數值進行索引,由您決定如何定義特定的查找機制。
  • 索引器可被重載。
  • 索引器可以有多個形參,例如當訪問二維數組時。

下例中,定義了一個泛型類,併爲其提供了簡單的 getset 訪問器方法

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]);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章