.NET Visual C#言語入門 > インデクサ
のぶ亭『プログラミングの相談窓口』 … 様々なプログラミング問題を個別対応致します |
インデクサ
オブジェクトを配列と同じようにインデックスを付けて参照することができます。
インデクサの概要
- getアクセサは値を返し、setアクセサは値を割り当てます。
- thisは、インデクサの定義に使用されます。
- valueは、setインデクサで割り当てられている値を定義するときに使用されます。
- インデクサは、整数値でインデックスを指定する必要はありません。
検索方法をどのように定義するかによって決めてください。 - インデクサはオーバーロードできません。
- インデクサには複数の仮パラメータを指定できます。
2次元の配列にアクセスする場合などです。
配列要素に数値を用いた例
class IndexerClass { private int[] arr = new int[100]; public int this[int index] { get { if (index < 0 || index >= 100) { return 0; } else { return arr[index]; } } set { if (!(index < 0 || index >= 100)) { arr[index] = value; } } } } class MainClass { static void Main() { IndexerClass test = new IndexerClass(); test[0] = 100; test[1] = 200; test[5] = 500; for (int Index = 0; Index <= 10; Index++) { System.Console.WriteLine( "Test Data #{0} = {1}", Index, test[Index]); } } }
配列要素に文字を用いた例
class DayCollection { string[] days = { "日", "月", "火", "水", "木", "金", "土" }; // 指定された曜日の要素値を返す public int this[string day] { get { return (GetDay(day)); } } // 指定された曜日の要素値を返す(検索処理) private int GetDay(string strDay) { int Index = 0; foreach (string day in days) { if (day == strDay) { return Index; } Index++; } return -1; } } class Program { static void Main(string[] args) { DayCollection week = new DayCollection(); System.Console.WriteLine(week["金"]); System.Console.WriteLine(week["陽"]); } }
イ
public interface IIndexerInterface { int this[int index] { get; set; } } class IndexerClass : IIndexerInterface { private int[] arr = new int[100]; public int this[int index] { get { if (index < 0 || index >= 100) { return 0; } else { return arr[index]; } } set { if (!(index < 0 || index >= 100)) { arr[index] = value; } } } } class MainClass { static void Main() { IndexerClass test = new IndexerClass(); test[0] = 100; test[1] = 200; test[5] = 500; for (int Index = 0; Index <= 10; Index++) { System.Console.WriteLine("Test Data #{0} = {1}", Index, test[Index]); } } }
ンターフェイスのインデクサ実装例
ジェネリッククラスでインデクサに対応した例
// ジェネリック・クラスが定義され、値の割り当てと取得を行う手段として // 単純なgetアクセサとsetアクセサのメソッドを定義しています class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } } class Program { static void Main(string[] args) { // SampleCollectionクラスのインスタンスを作成 SampleCollection<string> stringCollection = new SampleCollection<string>(); // 文字列の格納と参照を配列のように扱うことができます stringCollection[0] = "Hello, World"; System.Console.WriteLine(stringCollection[0]); } }