c#中的索引器

来源:互联网 发布:中国地图数据库 编辑:程序博客网 时间:2024/05/22 02:15

索引器属性  允许如对待数组 一样对待对象 ,允许类的客户代码 能在对象中进行索引,就好像对象是一个数组一样

C#代码 
  1. namespace test  
  2. {  
  3.     class MyList  
  4.     {  
  5.         protected ArrayList data = new ArrayList();  
  6.         public object this[int index]  
  7.         {  
  8.             get  
  9.             {  
  10.                 if (index > -1 && index < data.Count)  
  11.                 {  
  12.                     return (data[index]);  
  13.                 }  
  14.                 else  
  15.                 {  
  16.                     return null;  
  17.                 }  
  18.             }  
  19.             set  
  20.             {  
  21.                 if (index > -1 && index < data.Count)  
  22.                 {  
  23.                     data[index] = value;  
  24.                 }  
  25.                 else if (index == data.Count)  
  26.                 {  
  27.                     data.Add(value);  
  28.                 }  
  29.   
  30.             }  
  31.         }  
  32.     }  
  33.     class Program  
  34.     {  
  35.         static void Main(string[] args)  
  36.         {  
  37.             MyList l = new MyList();  
  38.             l[0] = "foo";  
  39.             l[1] = "aa";  
  40.             l[2] = "bb";  
  41.             Console.WriteLine("{0} {1} {2}",l[0],l[1],l[2]);  
  42.             Console.ReadKey();  
  43.         }  
  44.     }  
  45. }  
原创粉丝点击