arr[0] 来取东西,很方便。
box[0] 来取剑,岂不妙哉?
索引器就像是一种特殊的属性,关键字是 this。
class SwordBox
{
private string[] swords = new string[10];
// 定义索引器
public string this[int index]
{
get { return swords[index]; }
set { swords[index] = value; }
}
}
SwordBox box = new SwordBox();
// 像操作数组一样操作对象!
box[0] = "倚天剑";
box[1] = "屠龙刀";
Console.WriteLine(box[0]); // 输出:倚天剑
下标不一定是数字,也可以是字符串!
// 假设我们要通过剑的名字来查找它的排名
public int this[string name]
{
get
{
if (name == "倚天剑") return 1;
return 999;
}
}
// 使用:
int rank = box["倚天剑"]; // 1
Dictionary(字典)或者 List(列表)内部就是用了索引器。
做一个 MedicineCabinet(药柜)类。
内部有一个字符串数组存药名。
实现一个索引器,通过数字存取药名。
class MedicineCabinet
{
private string[] meds = new string[100];
public string this[int i]
{
get { return meds[i]; }
set { meds[i] = value; }
}
}