class SampleCollection
{
private T[] arr = new T[100];
public T this[int i]
{
get
{
return arr[i];
}
set
{
arr[i] = value;
}
}
}
// This class shows how client code uses the indexer
class Program
{
static void Main(string[] args
{
SampleCollection
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]
}
}
C# 并不将索引类型限制为整数。例如,对索引器使用字符串可能是有用的。通过搜索集合内的字符串并返回相应的值,可以实现此类的索引器。由于访问器可被重载,字符串和整数版本可以共存。
例子2:
// Using a string as an indexer value
class DayCollection
{
string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
// This method finds the day or returns -1
private int GetDay(string testDay
{
int i = 0;
foreach (string day in days
{
if (day == testDay
{
return i;
}
i++;
}
return -1;
}
// The get accessor returns an integer for a given string
public int this[string day]
{
get
{
return (GetDay(day
}
}
}
class Program
{
static void Main(string[] args
{
DayCollection week = new DayCollection(
System.Console.WriteLine(week["Fri"]
System.Console.WriteLine(week["Made-up Day"]
}
}