using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//C#索引器(Indexer)
/*
* 索引器(Indexer)允许一个对象可以像数组一样使用下标的方式来访问。
* 当你为类定义一个索引器时,该类的行为就会像一个虚拟数组(virtual array)一样。可以使用数组访问运算符[]来访问该类的成员。
* 语法
* 一维索引器的语法如下:
* element-type thi[int index]
* {
* //get访问器
* get
* {
* //返回index指定的值
* }
* //set访问器
* set
* {
* //设置index指定的值
* }
*
* }
*
* 用途
* 索引器的行为声明在某种程度上类似于属性(property)。就像属性(property),可以使用get和set访问器来定义索引器。但是,属性返回或设置一个特定的数据成员,而索引器返回或设置对象实例的一个特定值。换句话说,它把实例数据分为更小的部分,并索引每个部分,获取或设置每个部分。
* 定义一个属性(property)包含提供属性名称。索引器定义的时候不带有名称,但带有this关键字,它指向对象实例。
*
*/
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";
for(int i = 0;i < IndexedNames.size; i++)
{
Console.WriteLine(names[i]);
}
//重载索引器(Indexer)
/*
* 索引器(indexer)可被重载。索引器声明的时候也可带有多个参数,且每个参数可以是不同的类型。没有必要让索引器必须是整型的。C#允许索引器可以是其他类型,例如,字符串类型。
*
*/
IndexedNames2 names2 = new IndexedNames2();
names2[0] = "Zara";
names2[1] = "Riz";
names2[2] = "Nuha";
names2[3] = "Asif";
names2[4] = "Davinder";
names2[5] = "Sunil";
names2[6] = "Rubic";
for (int i = 0; i < IndexedNames2.size; i++)
{
Console.WriteLine(names[i]);
}
//使用重载索引器查询特定值的索引
Console.WriteLine("Nuha: {0}", names2["Nuha"]);
Console.ReadKey();
}
}
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;
}
}
}
}
class IndexedNames2
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames2()
{
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;
}
}
}
}