いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

インデクサ

javaから移ってきた人にとって、馴染みが薄いのが
インデクサ・デリゲート・演算子オーバーロード・パーシャルクラスとかではないでしょうか。


他は結構構文的には似ているのでわかりやすいはずです。


てことで、インデクサのちょこっとした自分用のメモです。

// vim:set ts=4 sw=4 et ws is nowrap ft=cs:

using System;
using System.Collections.Generic;

namespace Gsf.Samples.CSharp{

    public class IndexerSample : IExecutable{

        IList<string> _list;

        public IndexerSample(){
            _list = new List<string>();

            InitializeList();
        }

        void InitializeList(){
            string prefix = "value_";

            for(int i = 0; i < 10; i++){
                _list.Add(string.Format("{0}{1}", prefix, (i + 1)));
            }
        }

        /// <summary>
        /// インデクサメソッドです。
        /// </summary>
        public string this[int index]{
            get{
                return _list[index];
            }
            set{
                if(index > _list.Count){
                    for(int i = 0, diff = (index - _list.Count); i < diff; i++){
                        _list.Add(string.Empty);
                    }
                }

                _list.Add(value);
            }
        }

        public void Execute(){

            Console.WriteLine(this[0]);
            Console.WriteLine(this[1]);
            Console.WriteLine(this[8]);

            this[8] = "hoge";
            Console.WriteLine(this[8]);

            this[11] = "hehe";
            Console.WriteLine(this[11]);

            this[100] = "100";
            Console.WriteLine(this[100]);

            Console.WriteLine("'" + this[92] + "'");

            this[2000] = "gsf_zero1";
            Console.WriteLine(this[2000]);

            Console.WriteLine("'" + this[1998] + "'");
        }

        static void Main(){
            new IndexerSample().Execute();
        }
    }
}


インデクサは、

public 戻りの型 this[要素を特定するための引数]{
    get{
    }
    set{
    }
}


という感じで定義します。
サンプルでは、intを使用して数値のインデックスを指定できるよう
にしていますが、別にintでなくてもかまいません(stringとか)
また、[]内の引数の数も好きにできます。([int i, int j]とか)


内部には、プロパティと同じくget;set;が書けます。
また、プロパティと同じくgetだけ、setだけでもオッケイです。
その場合は、ReadOnly, WriteOnlyなインデクサになります。


.NETクラスライブラリには、インデクサを実装しているクラスが
たくさんあります。
たとえば、DataGridViewの場合、ある特定のセルを示すのに

_grid.Rows[n].Cells[m]

としてもDataGridViewCellオブジェクトがとれますが、

_grid[m, n]

としても取得できます。



================================
過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。