//c#索引器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 5;
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] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
// 使用帶有 int 參數的第一個索引器
for (int i = 0; i < IndexedNames.size; i++)
{
Console.WriteLine(names[i]);
}
// 使用帶有 string 參數的第二個索引器
Console.WriteLine(names["Nuha"]);
Console.ReadKey();
}
}
}
IndexerApplication
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.