using System; using System.Collections; //要用ArrayList要引用这个 class CourseScore { //普通的属性用法 private string name; private int courseID; private int score; public CourseScore(string name, int courseID, int score) { this.name = name; this.courseID = courseID; this.score = score; } public string Name { get { return name; } set { name = value; } } public int CourseID { get { return courseID; } set { courseID = value; } } public int Score { get { return score; } set { score = value; } } } class CourseScoreIndexer { //构造器 private ArrayList arrCourseScore; public CourseScoreIndexer() { arrCourseScore = new ArrayList(); } public int this[string name, int courseID] { //构造器只能用this get { foreach (CourseScore cs in arrCourseScore) { if (cs.Name == name && cs.CourseID == courseID) { return cs.Score; } } return -1; } set { arrCourseScore.Add(new CourseScore(name, courseID, value)); //hashtable用.Add } } public ArrayList this[string name] { get { ArrayList tempArr = new ArrayList(); foreach (CourseScore cs in arrCourseScore) { if (cs.Name == name) { tempArr.Add(cs); } } return tempArr; } } } class Test { static void Main() { CourseScoreIndexer csi = new CourseScoreIndexer(); csi["张三", 1] = 90; csi["张三", 2] = 80; csi["李四", 1] = 70; Console.WriteLine("张三的第2门课程分数为:" + csi["张三", 2]); ArrayList tempArr = csi["张三"]; foreach (CourseScore cs in tempArr) { Console.WriteLine("姓名:" + cs.Name + " 课程编号:" + cs.CourseID + " 分数:" + cs.Score); } Console.ReadKey(); } }