C#中的索引器允许对对象(例如数组)进行索引。定义一个类的索引器后,该类的行为类似于虚拟数组。然后,您可以使用数组访问运算符([])访问此类的实例。
索引器可能会超载。索引器也可以使用多个参数声明,并且每个参数可以是不同的类型。
以下是C#中重载索引器的示例-
using System;
namespace IndexerApplication {
class IndexedNames {
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames() {
for (int i = 0; i < size; i++) {
namelist[i] = "N. A.";
}
}
public string this[int index] {
get {
string tmp;
if( index >= 0 && index <= size-1 ) {
tmp = namelist[index];
} else {
tmp = "";
}
return ( tmp );
}
set {
if( index >= 0 && index <= size-1 ) {
namelist[index] = value;
}
}
}
public int this[string name] {
get {
int index = 0;
while(index < size) {
if (namelist[index] == name) {
return index;
}
index++;
}
return index;
}
}
static void Main(string[] args) {
IndexedNames names = new IndexedNames();
names[0] = "John";
names[1] = "Joe";
names[2] = "Graham";
names[3] = "William";
names[4] = "Jack";
names[5] = "Tom";
names[6] = "Tim";
//使用带有int参数的第一个索引器
for (int i = 0; i < IndexedNames.size; i++) {
Console.WriteLine(names[i]);
}
//使用第二个索引器和字符串参数
Console.WriteLine(names["Nuha"]);
Console.ReadKey();
}
}
}输出结果
John Joe Graham William Jack Tom Tim N. A. N. A. N. A. 10