using System;
public class Photo //这个类是一个相片类
{ private string _title; //相片标题//先定义默认构造函数public Photo(){ //初始化相片标题的构造方法 _title = "我是张三";}public Photo(string title){ //初始化相片标题的构造方法 _title = title;}public string Title{ //属性 get { return _title; }}}public class Album
{ //相册类Photo[]photos; //用于存放照片的数组public Album(){ //初始化相册大小 photos = new Photo[3];}public Album(int capacity){ //初始化相册大小 photos = new Photo[capacity];}//下面定义索引用于检索照片信息,带有int参数的Photo索引器public Photo this[int index]{ get //get方法用于根据索引从索引器中获取照片 { if (index < 0 || index >= photos.Length) //有效的索引 { Console.WriteLine("索引无效"); return null; } else { return photos[index]; } } set { if (index < 0 || index >= photos.Length) { Console.WriteLine("索引无效"); return ; //set 无返回 所以 return 就可以了。因为这里定义的是Photo类型,不是void类型。必写返回 } else { photos[index] = value; } }}//根据标题检索照片,但不能根据标题赋值,设置为只读索引。带有string参数的Photo索引器。public Photo this[string title]{ get { //遍历数组中所有照片 foreach (Photo p in photos) { if (p.Title == title) //判断 return p; } Console.WriteLine("没有该照片"); return null;//使用null指示失败 }}}class Test
{ static void Main(string[]arsg){ Album friends = new Album(3); //创建相册大小为3 //创建3张照片 Photo first = new Photo("逍遥"); Photo second = new Photo("太子"); Photo third = new Photo("姚佳"); friends[0] = first; friends[1] = second; friends[2] = third; //按照索引进行查询 Photo objPhoto = friends[2]; Console.WriteLine(objPhoto.Title); //按名称进行检查 Photo obj2Photo = friends["太子"]; Console.WriteLine(obj2Photo.Title);}}定义索引器的时候使用this关键字,get和set访问器和属性的访问器相同,索引器和数组的属性有点相似,只是数组只通过索引检索,而索引器可以通过重载,自定义访问方式。
注意:将数组作为对象对待更加直观时,才使用索引器。