インデクサー (C# プログラミング ガイド)

インデクサーを使用すると、配列と同じようにクラスまたは構造体のインスタンスにインデックスを作成することができます。 インデックス値は、型またはインスタンス メンバーの明示的な指定なしで設定または取得できます。 インデクサーはプロパティと似ていますが、そのアクセサーがパラメーターを取る点が異なります。

次の例は、値の割り当てと取得を行う単純な get アクセサー メソッドと set アクセサー メソッドを持つジェネリック クラスを定義します。 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 アクセサーは、値を返すか値を設定する単一のステートメントで構成します。 式の本文のメンバーは、このシナリオをサポートする簡略化された構文を提供します。 C# 6 以降、読み取り専用インデクサーは、次の例のように、式の本文のメンバーとして実装することができます。

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 キーワードは使用されないことに注意してください。

C# 7.0 以降、get アクセサーと set アクセサーのどちらも、式の本文のメンバーとして実装できます。 この場合、get キーワードと set キーワードの両方を使用する必要があります。 次に例を示します。

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 キーワードは、インデクサーの定義に使用されます。

  • アクセサーで割り当てる値は value キーワードを使用して定義します。

  • インデクサーは、整数値でインデックスを指定する必要はありません。個々の検索メカニズムの定義方法によります。

  • インデクサーはオーバーロードすることができます。

  • インデクサーには、2 次元配列にアクセスする場合など、複数の仮パラメーターを指定できます。

関連項目

C# 言語仕様

詳細については、「C# 言語の仕様」の「インデクサー」を参照してください。 言語仕様は、C# の構文と使用法に関する信頼性のある情報源です。

関連項目