先决条件: C#中的索引器
我们可以在C#中重载索引器。我们可以声明带有多个参数的索引器,并且每个参数都具有不同的数据类型。索引必须为整数类型不是强制性的。索引可以是不同的类型,例如字符串。
示例
using System;
using System.Collections;
namespace ConsoleApplication1
{
class Names
{
static public int len=10;
private string []names = new string[len] ;
public Names()
{
for (int loop = 0; loop < len; loop++)
names[loop] = "N/A";
}
public string this[int ind]
{
get
{
string str;
if (ind >= 0 && ind <= len - 1)
str = names[ind];
else
str = "...";
return str;
}
set
{
if (ind >= 0 && ind <= len - 1)
names[ind]=value;
}
}
public int this[string name]
{
get
{
int ind=0;
while (ind < len)
{
if (names[ind] == name)
return ind;
ind++;
}
return ind;
}
}
}
class Program
{
static void Main()
{
Names names = new Names();
names[0] = "Duggu";
names[1] = "Shaurya";
names[2] = "Akshit";
names[3] = "Shivika";
names[4] = "Veer";
//第一索引器
for (int loop = 0; loop < Names.len; loop++)
{
Console.WriteLine(names[loop]);
}
//第二索引器
Console.WriteLine("Index : "+names["Shaurya"]);
}
}
}输出结果
Duggu Shaurya Akshit Shivika Veer N/A N/A N/A N/A N/A Index : 1