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訪問器和屬性的訪問器相同,索引器和數組的屬性有點相似,只是數組只通過索引檢索,而索引器可以通過重載,自定義訪問方式。
注意:將數組作爲對象對待更加直觀時,才使用索引器。