官方描述:索引器允许类或结构的实例就像数组一样进行索引。索引器形态类似于,不同之处在于它们的取值函数采用参数。
索引器其实就是利用索引(index)找出具体数据的方法(函数),在类的设计中它并不是必须的,它是可以用普通函数替代的,简单点理解,其实就是函数的一种特殊写法而已
class Program { static void Main(string[] args) { People p = new People(); //使用索引器给类的两个属性赋值 p[0] = "张三"; p[1] = "李四"; p[2] = "王五"; p[3] = "王麻子"; Console.WriteLine("p[0]=" + p[0]); Console.WriteLine("p[1]=" + p[1]); Console.WriteLine("p[2]=" + p[2]); Sample s = new Sample(); Console.WriteLine(s[23]); Console.ReadLine(); } } public class Sample { public string this[int index] { get { return "当前索引号为:" + index; } } } public class People { private string[] name = new string[10]; //定义索引器,必须以this关键字定义,设置name字段的索引值为0,address字段的索引值为1 public string S { get; set; } public string this[int index] { get { return name[index]; } set { this.name[index] = value; } } }