什么是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 生日开业蛋糕祝福语简短