C#类索引器的使用

8/3/2015来源:C#应用人气:2118

C#类索引器的使用

索引器提供了一种可以让类被当作数组进行访问的方式。在C#中,类索引器是通过this的属性实现的。index.ToString("D2")将index转换成一个具有两个字符宽度的字符串usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceClassIndexer{///<summary>///defineaclasscalledAClass,whichhasonlyonePRivatevariable///</summary>classAClass{privatestring_name;publicstringName{get{returnthis._name;}set{this._name=value;}}publicAClass(stringname){this._name=name;}}///<summary>///AClassContainerclass///</summary>classAClassContainer{privateAClass[]_AClassList;publicAClassContainer(){this._AClassList=newAClass[10];}publicAClassContainer(intcap){this._AClassList=newAClass[cap];}///<summary>///classindexerbyusingint///</summary>///<paramname="index"></param>///<returns></returns>publicAClassthis[intindex]{get{if((index<0)||(index>this._AClassList.Length))returnnull;elsereturnthis._AClassList[index];}set{if((index<0)||(index>this._AClassList.Length))return;elsethis._AClassList[index]=value;}}///<summary>///classindexerbyusingstring///</summary>///<paramname="name"></param>///<returns></returns>publicAClassthis[stringname]{get{foreach(AClassclsinthis._AClassList){if(cls.Name==name)returncls;}returnnull;}}}classProgram{staticvoidMain(string[]args){intcount=10;AClassContainerclassContainer=newAClassContainer(count);for(intindex=0;index<count;index++){stringname=index.ToString("D2");classContainer[index]=newAClass(name);}for(intindex=0;index<count;index++){AClasscls=classContainer[index];System.Console.WriteLine("classContainer[{0}].Name=\"{1}\"",index,cls.Name);}System.Console.WriteLine();for(intindex=count-1;index>=0;index--){stringname=index.ToString("D2");AClasscls=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"