C#-索引器
2017-10-14 本文已影响0人
JervieQin
/// <summary>
/// 1.特点
/// C#索引器允许一个对象可以向数组一样被索引。当你为类定义一个索引器时,该类的行为就会像一个虚拟数组一样。你可以使用数组的访问运算符访问该类的实例。
/// 2.属性和索引器的比较
/// 索引器的行为在某种程度上有点向属性,都需要通过get,set作为访问器。
/// 但是属性需要属性名,而索引器需要一个this关键字替代,它指向对象实例。
/// 3.使用场景
/// C#中的类成员可以是任意类型,包括数组和集合。当一个类包含了数组和集合成员时,索引器将大大简化对数组或集合成员的存取操作。
/// </summary>
class Indexer
{
//存放名字的数组
private string[] namelist = new string[size];
static public int size = 10;
//定义构造函数,初始化名字列表
public Indexer() {
for (int i = 0; i < size; i++)
namelist[i] = "N.A.";
}
//定义一个一维索引器
public string this[int index]
{
//get访问器
get
{
string tmp;
if (index >= 0 && index <= size - 1)
tmp = namelist[index];
else
{
tmp = "";
}
//返回index指定的值
return (tmp);
}
//set访问器
set
{
if (index >= 0 && index <= size - 1)
namelist[index] = value;
}
}
//重载索引器
public int this[string name]
{
get {
int index = 0;
while (index < Indexer.size)
{
if (namelist[index] == name)
return index;
index++;
}
return index;
}
}
static void Main(string[] args)
{
Indexer indexr = new Indexer();
//使用索引器,内在行为是索引器中get,set的行为
indexr[0] = "Zara";
indexr[1] = "Riz";
indexr[2] = "Nuha";
indexr[3] = "Asif";
indexr[4] = "Davinder";
indexr[5] = "Sunil";
indexr[6] = "Rubic";
for (int i = 0; i < Indexer.size; i++)
{
Console.WriteLine(indexr[i]);
}
Console.WriteLine(indexr["Riz"]);
Console.ReadKey();
}
}