1. 用reflector反编译可以看出,索引器的内部本质上就是set_item和get_item方法;
2. 索引器允许类或结构的实例就像数组一样进行索引;
3. 索引器类似于属性,不同之处在于它们的访问器采用参数;
举个例子:
// 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; } // Theget accessor returns an integer for a given string publicint this[string day] { get { return (GetDay(day)); } } } class Program { staticvoid Main(string[] args) { DayCollection week = new DayCollection(); System.Console.WriteLine(week["Fri"]); System.Console.WriteLine(week["Made-up Day"]); } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
输出 5 -1
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|