【C#】インデクサ

インデクサ(Indexer)

プロパティのようなもので、あたかも配列変数にアクセスするかのようなソースコードを記述することによって、ユーザがあらかじめ記述したコードを実行させる機能

自作クラスにインデクサを定義


class Greeting{
    private List<string> Greet;
    
    public Greeting(){
        this.Greet = new List<string>
        {
            "Good Morning",
            "Hello",
            "Good Evening",
            "Good Night"
        };
    }
    
    public string this[int index]
    {
        get { return this.Greet[index]; }
        set { this.Greet[index] = value; }
    }
}
    

使用


static void Main()
{
    var greeting = new Greeting();
    System.Console.WriteList(greeting[0]);
}