//为了说明索引器而简化的控件类 public class ListBoxTest { private string[] strArray; private int ctr = 0; //控件的构造函数 public ListBoxTest(params string[] initStr) { //用于存储的数组(索引器用) strArray = new string[256]; //复制参数数组 foreach (string s in initStr) { strArray[ctr++] = s; } } //追加字符串用 public void Add(string theString) { if (ctr >= strArray.Length) { Console.WriteLine("超出最大范围!"); } else { strArray[ctr++] = theString; } } //索引器的定义,有些类似属性的调用 public string this[int index] { get { if (index < 0 || index >= strArray.Length) { Console.WriteLine("错误的索引值!"); } return strArray[index]; } set { if (index >= ctr) { Console.WriteLine("错误的索引值!"); } else { strArray[index] = value; } } } //为ListBoxTest的foreach定义GetEnumerator()方法,便于迭代 public IEnumerator GetEnumerator() { for (int i = 0; i < ctr; i++) { yield return strArray[i]; } } //用于返回已存储的数组容量 public int GetNumEntries() { return ctr; } } class Program { static void Main(string[] args) { //初期化 ListBoxTest lbt = new ListBoxTest("Hello","World"); //索引器调用赋值 lbt.Add(","); lbt.Add("How "); lbt.Add("are "); lbt.Add("you !"); lbt[1] = "Tom"; foreach (string s in lbt) { Console.WriteLine(s); } Console.Read(); } }