|
简单说来,所谓索引器就是一类特殊的属性,通过它们你就可以像引用数组一样引用自己的类。 声明方法如下(与属性相似):
//修饰符 类型名称 this [类型名称 参数名] public type this [int index] { get { //... } set { //... } } 用例子简单说明: using System.Collections;
static void Main(string[] args) { //调用IntBits.IntBits方法,意为将63赋给bits IntBits bits = new IntBits(63); //获得索引6的bool值,此时 bits[6]将调用索引器"public bool this[int index]"中的Get,值为True bool peek = bits[6]; Console.WriteLine("bits[6] Value: {0}",peek); bits[0] = true; Console.WriteLine();
Console.ReadKey(); }
struct IntBits { private int bits; public IntBits(int initialBitValue) { bits = initialBitValue; Console.WriteLine(bits); } //定义索引器 //索引器的“属性名”是this,意思是回引类的当前实例,参数列表包含在方括号而非括号之内。 public bool this [int index] { get { return true; } set { if (value) { bits = 100; } } }
备注:
所有索引器都使用this关键词来取代方法名。Class或Struct只允许定义一个索引器,而且总是命名为this。
索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。
get 访问器返回值。set 访问器分配值。
this 关键字用于定义索引器。
value 关键字用于定义由 set 索引器分配的值。
索引器不必根据整数值进行索引,由您决定如何定义特定的查找机制。
索引器可被重载。
索引器可以有多个形参,例如当访问二维数组时。
索引器可以使用百数值下标,而数组只能使用整数下标:如下列定义一个String下标的索引器 public int this [string name] {...}
|