当一个类中包含数组成员时,索引器的使用将很大程度上简化了对类中数组成员的使用;索引器的定义类似于属性,也具有get访问器和set访问器。
[修饰符] 数据类型 this [索引类型 index]
{
get{//返回类中数组某个元素}
set{//对类中数组元素赋值}
}
其中,数据类型是类中要存取的数组的类型;索引类型表示该索引器使用哪一个类型的索引来存取数组元素,可以是整型;也可以是字符串类型;this则表示所操作的是类对象的数组成员,可以把它理解为索引器的名字(注意:索引器不能自定义名称)。下面的代码演示了索引器的定义过程:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Indexer { public class Index { private int[] intArray = new int[10]; public int this[int index] { get { return intArray[index]; } set { intArray[index] = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Indexer { class Program { static void Main(string[] args) { Index index = new Index(); //为数组赋值 for (int i = 0; i < 10; i++) { index[i] = i; } //获取数组中的值 for (int i = 0; i < 10; i++) { if (i <= 8) { Console.Write(index[i] + ","); } else { Console.Write(index[i]); } } Console.ReadKey(); } } }
打印结果: