索引器允許類或結構的實例就像數組一樣進行索引。索引器類似於屬性,不同之處在於它們的訪問器采用參數。索引器經常是在主要用於封裝內部集合或數組的類型中實現的。
索引器概述
- 使用索引器可以用類似於數組的方式為對象建立索引;
- get訪問器返回值,set訪問器分配值;
- this關鍵字用於定義索引器;
- 索引器不必根據整數值進行索引,可以自定義查找機制;
- 索引器可被重載;
- 索引器可以有多個行參;
- 索引器必須是實例成員
簡單示例
public class Indexer<T> { private T[] _arr=new T[100]; public T this[int i] { get { return _arr[i]; } set { _arr[i] = value; } } }
簡單示例
public class Indexer<T>
{
string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
private int GetDay(string testDay)
{
for (int j = 0; j < days.Length; j++)
{
if (days[j] == testDay)
{
return j;
}
}
throw new System.ArgumentOutOfRangeException(testDay, "testDay must be in the form \"Sun\", \"Mon\", etc");
}
public int this[string day]
{
get
{
return (GetDay(day));
}
}
}
