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

インデクサーを使うと、クラスまたは構造体のインスタンスに、配列と同様にインデックスを付けることができます。 インデクサーはプロパティと似ていますが、インデクサーのアクセサーはパラメーターを受け取る点が異なります。

次の例では、ジェネリック クラスが定義され、値の割り当てと取得を行う手段として単純な get アクセサーと set アクセサーのメソッドが指定されています。 クラス 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]);
    }
}
// Output: 
// Hello, World.

注意

その他の例については、「関連項目」を参照してください。

インデクサーの概要

  • インデクサーを使用すると、配列と同じようにオブジェクトにインデックスを付けることができます。

  • get アクセサーは値を返します。 set アクセサーは値を割り当てます。

  • this キーワードは、インデクサーの定義に使用されます。

  • value キーワードは、set インデクサーで割り当てられている値を定義するときに使用されます。

  • インデクサーは、整数値でインデックスを指定する必要はありません。検索方法をどのように定義するかによって決めてください。

  • インデクサーはオーバーロードできません。

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

関連項目

C# 言語仕様

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

参照

関連項目

プロパティ (C# プログラミング ガイド)

概念

C# プログラミング ガイド