C# 索引器不限於整數。字串索引器可搜尋集合內字串並回傳對應值,可與整數索引器共存 (多載)。
class DayCollection
{
string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
private int GetDay(string testDay)
{
for (int i = 0; i < days.Length; i++)
if (days[i] == testDay) return i;
return -1;
}
public int this[string day]
{
get { return GetDay(day); }
}
}
// 使用
var week = new DayCollection();
Console.WriteLine(week["Fri"]); // 5
Console.WriteLine(week["Made-up Day"]); // -1
Length 屬性讓呼叫端預先驗證,或在索引器內部處理例外get/set 盡可能限制存取層級,特別是 set參考「非對稱存取子存取修飾詞」與「例外設計指導方針」。