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";
//using the first indexer with int parameter
for (int i = 0; i < IndexedNames.size; i++) {
Console.WriteLine(names[i]);
}
//using the second indexer with the string parameter
Console.WriteLine(names["Nuha"]);
Console.ReadKey();
}
}
}输出
John Joe Graham William Jack Tom Tim N. A. N. A. N. A. 10
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP