Indexer ทำให้ Object เข้าถึงได้แบบ Array (用 [ ]) Indexers สามารถ Overload ได้ และรับ Parameters หลายตัว ชนิดต่างกันได้
ตัวอย่าง Overloaded Indexers
using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++) namelist[i] = "N. A.";
}
// Indexer 1: int parameter
public string this[int index]
{
get
{
string tmp = "";
if (index >= 0 && index <= size - 1) tmp = namelist[index];
return tmp;
}
set
{
if (index >= 0 && index <= size - 1) namelist[index] = value;
}
}
// Indexer 2: string parameter
public int this[string name]
{
get
{
int index = 0;
while (index < size)
{
if (namelist[index] == name) return index;
index++;
}
return index;
}
}
static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "John"; names[1] = "Joe"; names[2] = "Graham";
names[3] = "William"; names[4] = "Jack"; names[5] = "Tom"; names[6] = "Tim";
// ใช้ Indexer int
for (int i = 0; i < IndexedNames.size; i++) Console.WriteLine(names[i]);
// ใช้ Indexer string
Console.WriteLine(names["Nuha"]); // 10 (Not found = size)
Console.ReadKey();
}
}
}
Output
John Joe Graham William Jack Tom Tim N. A. N. A. N. A. 10