C# 索引器

 1 using System;  
 2 using System.Collections.Generic;  
 3 using System.Text;  
 4 namespace Index  
 5 {  
 6     class sample<T>  //这个类告诉我们如何使用客户端代码索引器  
 7     {  
 8         private T[] arr = new T[100];  
 9         public T this[int i] //索引器的签名由其形参的数量和类型组成。  
10         {  
11             get { return arr[i];}  
12             set { arr[i] = value;}  
13         }  
14     }      
15     class IndexerClass  
16     {  
17         private int[] arr = new int[100]; //定义数组  
18         public int this[int index]   //索引器声明  
19         {  
20             get  
21             {  
22                 if (index < 0 || index >100)  return 0;  
23                 return arr[index];  
24             }  
25             set  
26             {  
27                 if (!(index < 0 || index > 100))  arr[index] = value;   
28             }  
29         }  
30     }  
31     class String_index  
32     {  
33         string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };  
34         private int GetDay(string testday)  
35         {  
36             int i = 0;  
37             foreach(string day in days)  
38             {  
39                 if (day == testday)  return i;  
40                 i++;  
41             }  
42             return -1;  
43         }  
44         public int this[string day]  
45         {  
46             get{ return GetDay(day); }  
47         }  
48     }  
49     class Program  
50     {  
51         static void Main(string[] args)  
52         {  
53             sample<string> string_value = new sample<string>();  
54             string_value[0] = "Hello world";  
55             System.Console.WriteLine(string_value[0]);  
56   
57             IndexerClass test = new IndexerClass();  
58             //调用索引器初始化第2、4个数据  
59             test[3] = 123;  
60             test[5] = 1024;  
61             for (int i = 0; i <= 10; i++ )  
62             { System.Console.WriteLine("数据为#{0} = {1}", i, test[i]);}  
63             String_index week = new String_index();  
64             System.Console.WriteLine("这是一周的第{0}天", week["Tues"]);  
65             Console.ReadKey();  
66         }  
67     }  
68 }  

 来源:http://blog.csdn.net/seawaywjd/article/details/7061155

posted @ 2014-08-27 15:25  吹小号的程序猿  阅读(134)  评论(0编辑  收藏  举报