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

索引子允許類別或結構的執行個體像陣列一樣地編製索引。 您不需明確指定型別或執行個體成員,就能設定或擷取已索引的值。 索引子和屬性類似,差異在於它們的存取子會採用參數。

下列範例定義具有簡單 getset 存取子方法的泛型類別來指派和擷取值。 Program 類別會建立此類別的執行個體以儲存字串。

using System;

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

   // Define the indexer to allow client code to use [] notation.
   public T this[int i]
   {
      get { return arr[i]; }
      set { arr[i] = value; }
   }
}

class Program
{
   static void Main()
   {
      var stringCollection = new SampleCollection<string>();
      stringCollection[0] = "Hello, World";
      Console.WriteLine(stringCollection[0]);
   }
}
// The example displays the following output:
//       Hello, World.

注意

如需更多範例,請參閱相關章節

運算式主體定義

通常會利用索引子的 get 或 set 存取子來組成要傳回或設定值的陳述式。 運算式主體成員提供簡化的語法來支援此案例。 可將唯讀索引子實作為運算式主體成員,如下列範例所示。

using System;

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

   // Define the indexer to allow client code to use [] notation.
   public T this[int i] => arr[i];

   public void Add(T value)
   {
      if (nextIndex >= arr.Length)
         throw new IndexOutOfRangeException($"The collection can hold only {arr.Length} elements.");
      arr[nextIndex++] = value;
   }
}

class Program
{
   static void Main()
   {
      var stringCollection = new SampleCollection<string>();
      stringCollection.Add("Hello, World");
      System.Console.WriteLine(stringCollection[0]);
   }
}
// The example displays the following output:
//       Hello, World.

請注意,=> 會引進運算式主體,且不使用 get 關鍵字。

可同時將 get 和 set 存取子實作為運算式主體成員。 在此情況下,必須同時使用 getset 關鍵字。 例如:

using System;

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

   // Define the indexer to allow client code to use [] notation.
   public T this[int i]
   {
      get => arr[i];
      set => arr[i] = value;
   }
}

class Program
{
   static void Main()
   {
      var stringCollection = new SampleCollection<string>();
      stringCollection[0] = "Hello, World.";
      Console.WriteLine(stringCollection[0]);
   }
}
// The example displays the following output:
//       Hello, World.

索引子概觀

  • 索引子可以讓物件利用與陣列類似的方式編製索引。

  • get 存取子會傳回值。 set 存取子會指派值。

  • this 關鍵字是用來定義索引子。

  • valueset 關鍵字是用來定義 存取子要指派的值。

  • 索引子不一定要由整數值編製索引。您可自行決定如何定義特定的查詢機制。

  • 索引子可以多載。

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

相關章節

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格中的索引子。 語言規格是 C# 語法及用法的限定來源。

另請參閱