using System; using System.Collections.Generic; using System.Text; //使用索引器 namespace interfaceDemo { public class Photo//相片类 { string title; public Photo(string title)//构造方法 { this.title = title; } public string Title//声明一个只读属性 { get { return this.title; } } } class Album//相册类 { Photo[] photos;//通过此数组存放相片 public Album(int num)//初始化相册容量 { photos = new Photo[num]; } public Photo this[int index]//定义一个可读写的索引器,可实现按序号读写 { get { return this.photos[index]; } set { this.photos[index] = value; } } public Photo this[string title]//重载一个只读索引器,按标题查找 { get { for (int i = 0; i < photos.Length; i++) { if (photos[i].Title == title)//判断标题是否相同 { return photos[i]; } } Console.WriteLine("没有找到"); return null; } } } class TestIndexDemo { static void Main(string[] args) { Photo first = new Photo("first"); Photo second = new Photo("second"); Album ab = new Album(20); ab[0] = first;//使用第一个索引器将照片存入相册中 ab[1] = second; Photo obj = ab[1];//使用第一个索引器根据序号读取相册中的照片 Console.WriteLine(obj.Title); obj = ab["first"];//使用第二个索引器根据标题取出照片 Console.WriteLine(obj.Title); Console.ReadLine(); } } }