C# 索引器
使用索引器的目的是为了能够像数组一样访问类中的数组型的对象。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SuoYinQiTest { class Persons { private int currentIndex = 0; private String[] names = new String[10]; public String this[int index]{ get { return names[index]; } set { names[index] = value; currentIndex++; } } public void printAll() { for (int i = 0; i < currentIndex; i++) { Console.WriteLine(names[i]); } Console.WriteLine("输出完毕"); } } class Program { static void Main(string[] args) { Persons persons = new Persons(); persons[0] = "zhangsan"; persons[1] = "lisi"; persons.printAll(); Console.Read(); } } }
本文出自 无忧之路 - 博客园