什么是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 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短