当一个类包含数组成员是,索引器的使用将大大地简化对类中数组成员的访问。索引器的定义类似于属性,也具有get访问器和set访问器,具体定义的形式如下:
[修饰符] 数据类型 this[索引类型 index]
{
get { //返回类中数组的某个元素 }
set { //对类中数组元素赋值}
}
其中,数据类型是类中要存取的数组的类型;索引类型表示该索引器使用哪一个类型的索引来存取数组元素,可以是整型,也可以是字符串类型;this则表示所操作的是类对象的数组成员,可以简单地把它理解为索引器的名字(注意:索引器不能自定义名称)。
下面代码示例索引器的定义过程:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp { class Student { private string[] stuArr = new string[3]; //可容纳3个字符串的字符串数组 public string this[int index] //索引器的定义 { get { return stuArr[index]; } set { stuArr[index] = value; } } } }
以上代码定义了一个索引器,索引器可以让我们像访问数组一样访问类中的数组成员,下面代码示例演示了如何使用索引器:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp { class Program { static void Main(string[] args) { Student stu = new Student(); //通过索引器对类中的数组进行赋值 stu[0] = "张三"; stu[1] = "李四"; stu[2] = "王五"; Console.WriteLine(stu[0]); //输出了张三 Console.WriteLine(stu[1]); //输出了李四 Console.WriteLine(stu[2]); //输出了王五 Console.ReadKey(); } } }
以上代码可以看出,索引器也是一种针对私有字段进行访问的方式,但此时的私有字段是数组类型,而属性则一般只对简单数据类型的私有字段进行访问。
文章评论