索引器提供了一种可以让类被当作数组进行访问的方式。在C#中,类索引器是通过this的属性实现的。
index.ToString("D2")将index转换成一个具有两个字符宽度的字符串
class="brush:csharp;gutter:true;">using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ClassIndexer { /// <summary> /// define a class called AClass,which has only one private variable /// </summary> class AClass { private string _name; public string Name { get { return this._name; } set { this._name = value; } } public AClass(string name) { this._name = name; } } /// <summary> /// AClassContainer class /// </summary> class AClassContainer { private AClass[] _AClassList; public AClassContainer() { this._AClassList = new AClass[10]; } public AClassContainer(int cap) { this._AClassList = new AClass[cap]; } /// <summary> /// class indexer by using int /// </summary> /// <param name="index"></param> /// <returns></returns> public AClass this[int index] { get { if ((index < 0) || (index > this._AClassList.Length)) return null; else return this._AClassList[index]; } set { if ((index < 0) || (index > this._AClassList.Length)) return; else this._AClassList[index] = value; } } /// <summary> /// class indexer by using string /// </summary> /// <param name="name"></param> /// <returns></returns> public AClass this[string name] { get { foreach (AClass cls in this._AClassList) { if (cls.Name == name) return cls; } return null; } } } class Program { static void Main(string[] args) { int count = 10; AClassContainer classContainer = new AClassContainer(count); for (int index = 0; index < count; index++) { string name = index.ToString("D2"); classContainer[index] = new AClass(name); } for (int index = 0; index < count; index++) { AClass cls = classContainer[index]; System.Console.WriteLine("classContainer[{0}].Name=\"{1}\"",index,cls.Name); } System.Console.WriteLine(); for (int index = count - 1; index >= 0; index--) { string name = index.ToString("D2"); AClass cls = classContainer[name]; System.Console.WriteLine("classContainer[{0}].Name=\"{1}\"",name,cls.Name); } System.Console.ReadLine(); } } } 结果: classContainer[0].Name="00" classContainer[1].Name="01" classContainer[2].Name="02" classContainer[3].Name="03" classContainer[4].Name="04" classContainer[5].Name="05" classContainer[6].Name="06" classContainer[7].Name="07" classContainer[8].Name="08" classContainer[9].Name="09" classContainer[09].Name="09" classContainer[08].Name="08" classContainer[07].Name="07" classContainer[06].Name="06" classContainer[05].Name="05" classContainer[04].Name="04" classContainer[03].Name="03" classContainer[02].Name="02" classContainer[01].Name="01" classContainer[00].Name="00"