类索引器是一种特殊的类成员,它的作用是让对象可以以类似数组的方式来存取。
数据结构如下:
[访问修饰符]数据类型 this [索引类型 index] { set{//设置属性的代码} get{//获得属性的代码} }
其中:数据类型是要存取数组的数据类型
索引器类型是表示索引器使用哪一种类型的索引来存取数组,可以是数组也可以是字符串
索引器的使用:对象名[索引]
索引器的用法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 索引器 { class Program { static void Main(string[] args) { //属性的用法 People person1 = new People(); person1.Age = "tom"; Console.WriteLine(person1.Age); //索引器的用法 People person2 = new People(); person2[5] = 100; person2[9] = 10; for(int i =0;i<10;i++) { Console.WriteLine(person2[i]); } while (true) { }; } } class People { //属性的用法 string name; public string Age { get { return name; } set { name = value; } } //索引器的用法 long[] number = new long[10]; public long this[int dex] { get { return number[dex]; } set { number[dex] = value; } } } }