using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ClassIndexTest { class IndexTest { private int[] myint = new int[10]; public int this[int index] { get { if(index>=0 && index<=9) return myint[index]; else return 0; } set { if (index >= 0 && index <= 9) myint[index] = value; } } } class WeekDay { private string[] weeks = { "星期一","星期二","星期三","星期四","星期五","星期六","星期日"}; private int GetDay(string weekday) { int i = 1; foreach (string week in weeks) { if (week == weekday) return i; i++; } return 0; } public int this[string week] { get { return GetDay(week); } } } class Program { static void Main(string[] args) { //访问类实例 IndexTest array = new IndexTest(); array[0] = 11; array[-5] = 12; array[3] = 14; array[5] = 15; array[11] = 16; Console.WriteLine("array[0]={0}", array[0]); Console.WriteLine("array[-5]={0}", array[-5]); Console.WriteLine("array[3]={0}", array[3]); Console.WriteLine("array[5]={0}", array[5]); Console.WriteLine("array[11]={0}", array[11]); Console.WriteLine("array[6]={0}", array[6]); //访问类成员 WeekDay weekday = new WeekDay(); Console.WriteLine(weekday["星期一"]); Console.WriteLine(weekday["星期二"]); Console.WriteLine(weekday["星期五"]); Console.WriteLine(weekday["星期八"]); Console.ReadKey(); } } }