面向对象基础——索引器

  C#中的string是可以通过索引器来访问对象中的字符,但却不能修改字符的值。

  我们来看string中关于索引器的定义,如下图。

  上图中索引器如同属性一样,具有get方法,却没有set方法,所以这就是为什么C#中的string类型的变量都是只读的。

  

  现在让我们来编写属于自己的索引器:

 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             Test test = new Test();
 6             Console.WriteLine("test[1] = {0},test[2] = {1}",test[1],test[2]);
 7 
 8             test[1] = "蔡升晏";
 9             test[2] = "石锦航";
10             Console.WriteLine("test[1] = {0},test[2] = {1}", test[1], test[2]);
11 
12             Console.WriteLine("索引器的重载:" + test["温尚翊",5]);
13         }
14     }
15 
16     public class Test 
17     {
18         private string name1 = "陈信宏";
19         private string name2 = "刘冠佑";
20 
21         public string this[int index] 
22         {
23             get
24             {
25                 if (index == 1)
26                 {
27                     return name1;
28                 }
29                 else if(index == 2)
30                 {
31                     return name2;
32                 }
33                 else
34                 {
35                     throw new Exception("索引的值超出了范围");
36                 }
37             }
38             set 
39             {
40                 if (index == 1)
41                 {
42                     name1 = value;
43                 }
44                 else if (index == 2)
45                 {
46                     name2 = value;
47                 }
48                 else
49                 {
50                     throw new Exception("索引的值超出了范围");
51                 }
52             }
53         }
54         //索引器也是可以重载的
55         public string this[string str, int x] 
56         {
57             get 
58             {
59                 return str + x;
60             }
61         }
62     }

  输出结果:

  我们看到,索引器像属性一样,具有get和set方法;又可以像类中的函数一样,可以被重载。

  在ADO.NET技术中,索引器经常被频繁地使用。

posted @ 2015-05-11 19:00  苏打兴  阅读(207)  评论(0编辑  收藏  举报