1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4
 5namespace CSharpFoundationStudy
 6{
 7    /*
 8     * 索引器 indexer
 9     * 实现索引指示器(indexer)的类可以象数组那样使用其实例后的对象,但与数组不同的是索引指示器的参数类型不仅限于int
10     * 属性与索引器的区别:
11     *   类的每一个属性都必须拥有唯一的名称,而类里定义的每一个索引器都必须拥有唯一的签名(signature)或者参数列表(这样就可以实现索引器重载)
12     *   属性可以是static(静态的)而索引器则必须是实例成员
13     *   为索引器定义的访问函数可以访问传递给索引器的参数,而属性访问函数则没有参数
14     */

15    public class Indexer
16    {
17        public string this[int index]
18        {
19            get
20            {
21                switch (index)
22                {
23                    case 0:
24                        return "Sunday";
25                    case 1:
26                        return "Monday";
27                    case 2:
28                        return "Thursday";
29                    case 3:
30                        return "Wednsday";
31                    case 4:
32                        return "Tuesday";
33                    case 5:
34                        return "Friday";
35                    case 6:
36                        return "Saturday";
37                    default:
38                        return "Error";
39                }

40            }

41        }

42
43        public string this[string day]
44        {
45            get
46            {
47                switch(day)
48                {
49                    case "Sun":
50                        return "Sunday";
51                    case "Mon":
52                        return "Monday";
53                    case "Thu":
54                        return "Thursday";
55                    case "Wed":
56                        return "Wednsday";
57                    case "Tue":
58                        return "Tuesday";
59                    case "Fri":
60                        return "Friday";
61                    case "Sat":
62                        return "Saturday";
63                    default:
64                        return "Error";
65                }

66            }

67        }

68
69        public string this[int index, string day]
70        {
71            get
72            {
73                if (index == 0 && day == "Sun")
74                    return "Sunday";
75                else if (index == 6 && day == "Sat")
76                    return "Saturday";
77                return "Error";
78            }

79        }

80    }

81
82    //public class IndexerTest
83    //{
84    //    public static void Main()
85    //    {
86    //        Indexer indexer = new Indexer();
87    //        Console.WriteLine("indexer[5] = {0}",indexer[5]);
88    //        Console.WriteLine("indexer['Wed'] = {0}",indexer["Wed"]);
89    //        Console.WriteLine("indexer[0, 'Sun'] = {0}", indexer[0, "Sun"]);
90    //        Console.ReadLine();
91    //    }
92    //}
93}

94
posted on 2008-01-20 20:27  simply-zhao  阅读(157)  评论(0编辑  收藏  举报