C#索引器
索引器(Indexer)允许一个对象可以像数组一样被索引。当为一个类定义了一个索引器后,这个类就会像一个虚拟数组一样,可以使用数组访问运算符[]来访问类的实例。
- 一维索引器的语法
element-type this[int index]
{
//get访问器
get
{
//返回index指定值
}
//set访问器
set
{
//设置index指定值
}
}
- 索引器Indexer作用
索引器的行为的声明有点像属性,可以使用get、set方法来定义索引器。
属性用来返回或设置一个特定的数据成员,而索引器返回或设置对像实例的一个特定值。
定义属性时包括提供属性名称。索引器定义的时候不带有名称,但带有this关键字,它指向对象实例。
使用Visual Studio 新建C#控制台应用程序chapter22_004
private string[] namelist = new string[size];
static public int size = 5;
public IndexNames()
{
for (int i = 0; i < size; i++)
{
namelist[i] = "未知";
}
}
//索引器
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;
}
}
}
在Main方法中添加如下测试代码
IndexNames names = new IndexNames();
names[0] = "谢声";
names[1] = "advent";
names[2] = "xiaoxie";
for (int i = 0; i < IndexNames.size; i++)
{
Console.WriteLine(names[i]);
}
Console.ReadKey();
编译运行后结果如下:

- Indexer索引器重载
索引器Indexer可以被重载,索引器声明的时候也可以带多个参数,并且每个参数都可以是不同的类型,注意:不一定索引器是整型的,可以是其它的类型。
在上面的代码中添加一个新的索引器,其中返回的是一个int型数字,参数是一个string
//索引器
public int this[string name]
{
get
{
int index = 0;
while (index < size)
{
if (namelist[index] == name)
{
return index;
}
index++;
}
return index;
}
}
在Main方法中添加如下代码对上面这个索引器进行测试
//使用string参数的第二个索引器
Console.WriteLine(names["xiaoxie"]);
最后整体编译运行后的结果如下:



被折叠的 条评论
为什么被折叠?



