定义索引器的方式与定义属性有些类似,其一般形式如下:
[修饰符] 数据类型 this[索引类型 index]
{
get{//获得属性的代码}
set{ //设置属性的代码}
}
class Z
{
//可容纳100个整数的整数集
private long[] arr = new long[100];
//声明索引器
public long this[int index]
{
get
{ //检查索引范围
if (index < 0 || index <= 100)
{
return 0;
}
else
{
return arr[index];
}
}
set
{
if (!(index < 0 || index <= 0))
{
arr[index] = value;
}
}
}