 インデクサも、配列のにように2次元、3次元、...と多次元のものを作ることができます。
インデクサも、配列のにように2次元、3次元、...と多次元のものを作ることができます。
宣言の仕方は、次のように行います。
要素のデータ型 this[int index1, int index2,...]{}
では、早速2次元の場合のサンプルをみてみましょう。
// mindexer01.cs
using System;
class MyClass
{
    int[,] array;
    public int this[int x, int y]
    {
        get
        {
            return array[x, y];
        }
        set
        {
            array[x, y] = value;
        }
    }
    public MyClass(int a, int b)
    {
        array = new int[a, b];
    }
}
class mindexer01
{
    public static void Main()
    {
        MyClass mc = new MyClass(4, 4);
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                mc[i, j] = i + j;
            }
        }
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                Console.WriteLine("{0} + {1} = {2}", i, j, mc[i, j]);
            }
        }
    }
}
使い方は1次元の時と全く同じです。実行結果は次のようになります。
 
もちろん、多次元インデクサでもインデックスにint型以外のものを使えます。
次の例は、インデックスにstring型とint型を使ったかなり変なプログラムです。 (なお、このプログラムの地名や市外局番は架空のものです)
// mindexer02.cs
using System;
class MyTelephone
{
    public string this[string address, int phone]
    {
        get
        {
            switch (address)
            {
                case "北海道":
                    switch (phone)
                    {
                        case 166:
                            return "旭川市";
                        case 11:
                            return "札幌市";
                        default:
                            return "知りません";
                    }
                case "東京都":
                    switch (phone)
                    {
                        case 3:
                            return "23区";
                        case 422:
                            return "小金井市";
                        default:
                            return "知りません";
                    }
                default:
                    return "知りません";
            }
        }
    }
}
class mindexer02
{
    public static void Main()
    {
        string strFormat = "{0}で市外局番が{1}は{2}です";
        MyTelephone mt = new MyTelephone();
        Console.WriteLine(strFormat, "東京都", 3, mt["東京都", 3]);
        Console.WriteLine(strFormat, "北海道", 166, mt["北海道", 166]);
        Console.WriteLine(strFormat, "九州", 114, mt["九州", 114]);
    }
}
これは、変なプログラムですね。まさか、インデクサに電話帳みたいなことをさせるとは
あまり思いつく人はいないでしょう。実行結果は次のようになります。
 
Update 07/Sep/2006 By Y.Kumei