Indexer ทำให้ออบเจกต์เข้าถึงได้เหมือน Array ด้วย [] สามารถ Overload ได้หลายรูปแบบ (พารามิเตอร์ต่างชนิด/จำนวน)
ตัวอย่าง: Indexer หลายรูปแบบ
using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[10];
static public int Size = 10;
public IndexedNames()
{
for (int i = 0; i < Size; i++)
namelist[i] = "N. A.";
}
// Indexer แบบ int (เข้าถึงด้วยดัชนี)
public string this[int index]
{
get
{
if (index >= 0 && index <= Size - 1)
return namelist[index];
return "";
}
set
{
if (index >= 0 && index <= Size - 1)
namelist[index] = value;
}
}
// Indexer แบบ string (ค้นหาด้วยชื่อ คืน Index)
public int this[string name]
{
get
{
for (int i = 0; i < Size; i++)
{
if (namelist[i] == name)
return i;
}
return Size; // ไม่พบ
}
}
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 < Size; i++)
Console.WriteLine(names[i]);
// ใช้ Indexer แบบ string
Console.WriteLine(names["Nuha"]); // 10 (ไม่พบ)
}
}
}
ผลลัพธ์
John Joe Graham William Jack Tom Tim N. A. N. A. N. A. 10
จุดสำคัญ
- Indexer ใช้
this[parameters]Syntax - ต้องมีอย่างน้อย 1 พารามิเตอร์
- Overload ได้โดยพารามิเตอร์ต่างชนิด/จำนวน
- มี get/set เหมือน Property