第十六章 索引器
1.索引器类似于属性,使用一个或多个参数引用属性,索引值指定要访问哪一个元素。
class Wrapper
{
private int [] bottle;
// 属性
public int [] Bottle
{
get => this.bottle;
set => this.bottle = value;
}
// 索引器
public int this [int i]
{
get => return this.bottle[i];
set => this.bottle[i] = value;
}
}
public static void Main(string [] args)
{
Wrapper w = new Wrapper();
int [] data = new int[]{2,8,1,6,5};
// 测试属性
w.Bottle = data;
// 测试索引器
w[0] = data[0];
w[2] = data[2];
w[4] = data[4];
}
2.关于索引器
a, 索引器由this关键字引入。在this之前指定索引器的返回值类型。在this之后的[]中指定索引器的索引值类型。
b, 索引器使用this关键字取代方法名。每个类或结构只允许定义一个索引器(可以重载),而且总是命名为this。
c, 索引器和属性一样,也包含get和set这两个访问器。
d, 索引器[]中声明的索引值,指定要访问哪一个元素。

浙公网安备 33010602011771号