索引器又称为带参数的属性,声明方式于属性相似 但索引的名称必须是关键字this,后一定接方括号[],[]间指定索引参数 索引器不能被定义为静态成员,只能为实例成员 //Team类实现两个索引器 class Team { private string[] member; private System.Collections.Hashtable ht = new System.Collections.Hashtable(); /* 索引器名称必须this关键字 */ //索引器参数为int类型 public string this[int index] { get { return member[index]; } set { member[index] = value; } } //索引器参数为string类型 public string this[string key] { get { return ht[key].ToString(); } set { ht[key] = value; } } //构造函数 public Team(int maxNum) { member = new string[maxNum]; } } class Program { //程序入口 static void Main() { Team team = new Team(8); //赋值 team[0] = "a"; team[1] = "b"; team["a"] = "1"; team["b"] = "2"; //取值 Console.WriteLine(team[0] + "," + team["a"]); //输出:a,1 Console.ReadLine(); } }