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

索引子允許類別或結構的執行個體像陣列一樣地編製索引。Indexers allow instances of a class or struct to be indexed just like arrays. 您不需明確指定型別或執行個體成員,就能設定或擷取已索引的值。The indexed value can be set or retrieved without explicitly specifying a type or instance member. 索引子和屬性類似,差異在於它們的存取子會採用參數。Indexers resemble properties except that their accessors take parameters.

下列範例定義具有簡單 getset 存取子方法的泛型類別來指派和擷取值。The following example defines a generic class with simple get and set accessor methods to assign and retrieve values. Program 類別會建立此類別的執行個體以儲存字串。The Program class creates an instance of this class for storing strings.

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.

注意

如需更多範例,請參閱相關章節For more examples, see Related Sections.

運算式主體定義Expression Body Definitions

通常會利用索引子的 get 或 set 存取子來組成要傳回或設定值的陳述式。It is common for an indexer's get or set accessor to consist of a single statement that either returns or sets a value. 運算式主體成員提供簡化的語法來支援此案例。Expression-bodied members provide a simplified syntax to support this scenario. 從 C# 6 開始,可將唯讀索引子實作為運算式主體成員,如下列範例所示。Starting with C# 6, a read-only indexer can be implemented as an expression-bodied member, as the following example shows.

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 關鍵字。Note that => introduces the expression body, and that the get keyword is not used.

從 C# 7.0 開始,可同時將 get 和 set 存取子實作為運算式主體成員。Starting with C# 7.0, both the get and set accessor can be an implemented as expression-bodied members. 在此情況下,必須同時使用 getset 關鍵字。In this case, both get and set keywords must be used. 例如:For example:

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.

索引子概觀Indexers Overview

  • 索引子可以讓物件利用與陣列類似的方式編製索引。Indexers enable objects to be indexed in a similar manner to arrays.

  • get 存取子會傳回值。A get accessor returns a value. set 存取子會指派值。A set accessor assigns a value.

  • this 關鍵字是用來定義索引子。The this keyword is used to define the indexer.

  • valueset 關鍵字是用來定義 索引子要指派的值。The value keyword is used to define the value being assigned by the set indexer.

  • 索引子不一定要由整數值編製索引。您可自行決定如何定義特定的查詢機制。Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.

  • 索引子可以多載。Indexers can be overloaded.

  • 索引子可具有一個以上的型式參數,例如,存取二維陣列時。Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.

相關章節Related Sections

C# 語言規格C# Language Specification

如需詳細資訊,請參閱 C# 語言規格中的索引子For more information, see Indexers in the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

另請參閱See also