ブラケットを用いてクラスに配列表現を加えるインデクサを学ぼう。

●Colors.cs

using System;
using System.Collections.Generic;

namespace IndexerLesson
{
    public class Colors
    {
        private string[] data = { "赤", "青", "黄" };
       
         //アクセス 戻り値 this[型 引数]
        public string this[int index]{
            set{
                this.data[index] = value;
            }
            get{
                return data[index];
            }
        }

    }
}

●Program.cs

using System;

namespace IndexerLesson
{
    class Program
    {
        static void Main(string[] args)
        {
            Colors colors = new Colors();
            for (int i = 0; i < 3;i++){
                Console.WriteLine(colors[i]);
            }
            colors[0] = "黒";
            Console.WriteLine(colors[0]);

        }
    }
}

オーバーロード可能
●JMonth.cs

using System;
using System.Collections.Generic;

namespace IndexerLesson
{
    public class JMonth
    {
        private string[] months = { "睦月", "如月", "弥生", "卯月", "皐月", "水無月", "文月", "葉月", "長月", "神無月", "霜月", "師走" };
        public string this[int index]{
            get{
                return months[index - 1];
            }
        }
        public int this[string name]{
            get{
                return Array.IndexOf(months, name) + 1;
            }
        }

    }
}

●Program.cs

using System;
using System.Collections.Generic;

namespace IndexerLesson
{
    class Program
    {
        static void Main(string[] args)
        {
            JMonth jMonth = new JMonth();
            Console.WriteLine(jMonth[6]);
            Console.WriteLine(jMonth["神無月"]);
        }
    }
}