インデクサーを使うと、オブジェクトの値をインデックス演算子[]で取得したり設定したりできます。インデクサーは引数を1つ取り、getとsetの両方、またはいずれか一方を持てます。インデクサーのsetの部分には特別なvalueという値があり、これがインデクサーに渡された値になります。
class LapTimes
{
private int[] times = new[] { 2, 4, 3, 8 };
public int this[int lap]
{
get { return times[lap]; }
set { times[lap] = value; }
}
}
var lapTimes = new LapTimes();
// Use the getter
Console.WriteLine(lapTimes[1]); // => 4
// Use the setter
lapTimes[2] = 5;
Console.WriteLine(lapTimes[2]); // => 5
インデクサーのsetの部分を省略すると、読み取り専用のインデクサーになります。式形式の本体を使うと、読み取り専用のインデクサーをより簡潔に定義できます。
class LapTimes
{
private int[] times = new[] { 2, 4, 3, 8 };
public int this[int lap] => times[lap];
}
インデクサーの仮引数はintである必要はなく、どんな型でもかまいません。
class LapTimes
{
// ...
public int this[string lap] => times[Convert.ToInt32(lap)];
}
インデクサーはオーバーロードすることもできます。
class LapTimes
{
public int this[int lap] => times[lap];
public int this[string lap] => times[Convert.ToInt32(lap)];
}