// 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"]); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 输出 5 -1 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |