什么是C#中的重载索引器?
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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短