c#定义的集合类型包括Array、List、Queue、Stack等,其中数组类型是唯一一个提供内置支持的集合类型,包括内置索引器,可通过[]实现,支持排序和反序等。
若一个类中包含数组类型,则可为该类创建索引器,已实现该数组的访问。
using System ;using System . Collections . Generic ;using System . Linq ;using System . Text ;namespace IndexDemo{class ListBoxTest{//static void Main(string[] args)//{//}private string [] strings ;private int cnt = 0 ;public ListBoxTest ( params string [] initialstrings ){strings = new string [ 256 ];foreach ( string s in initialstrings ){strings [ cnt ++] = s ;}}public void Add ( string theString ){if ( cnt > strings . Length ){Console . WriteLine ( "the array is out of size." );}elsestrings [ cnt ++]= theString ;}//索引public string this[int index]{get{if (index < 0 || index > strings.Length){Console.WriteLine("out of size");return "error";}elsereturn strings[index];}set{if (index < 0 || index > strings.Length)Console.WriteLine("out of size");elsestrings[index] = value;}}private int findstring ( string searchstring ){for ( int i = 0 ; i < strings . Length ; i ++)if ( strings [ i ]. StartsWith ( searchstring ))return i ;return - 1 ;}//索引器重载public string this[string index]{get{if (index.Length == 0){Console.WriteLine("index setting error.");}return this[findstring(index)];}set{strings[findstring(index)]=value;}}public int GetNumEntries (){return cnt ;}}public class Tester{static void Main (){ListBoxTest mbl = new ListBoxTest ( "hello" , "world" );mbl . Add ( "one" );mbl . Add ( "two" );mbl . Add ( "three" );mbl . Add ( "four" );mbl [ 3 ] = "test" ;mbl [ "th" ]= "override1" ;mbl [ "fo" ]= "override2" ;for ( int i = 0 ; i < mbl . GetNumEntries (); i ++)Console . WriteLine ( "lbt.strings[{0}]={1}" , i , mbl [ i ]);}}}