C# - 索引器

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace 索引器
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             var names = new IndexedNames();
13             names[0] = "这是";
14             names[1] = "一个";
15             names[2] = "关于";
16             names[3] = "索引器";
17             names[4] = "";
18             names[5] = "例子";
19             names[6] = "!";
20             names[7] = "..";
21             names[8] = "..";
22             names[9] = "....";
23             for (int i = 0; i < 10; ++i )
24             {
25                 Console.WriteLine(names[i]);
26             }
27             Console.ReadLine();
28         }
29     }
30 
31     /// <IndexedNames> 索引器类
32     /// 
33     /// </IndexedNames>
34     class IndexedNames
35     {                                                              
36         private string[] name_list = new string[10];
37         // 构造
38         public IndexedNames()
39         {
40             for (int i = 0; i < name_list.Length; ++i )
41             {
42                 name_list[i] = "N/A";
43             }
44         }
45         /// <索引器> 属性
46         /// </索引器>
47         /// <param name="index">索引
48         /// </param>
49         /// <returns>返回一个字符串
50         /// </returns>
51         public string this[int index]
52         {
53             // get方法
54             get     
55             {
56                 string tmp;
57                 if (index>=0&&index<=name_list.Length-1)
58                 {
59                     tmp = name_list[index];
60                 }
61                 else
62                 {
63                     tmp = "";
64                 }
65                 return tmp;
66             }
67             // set方法
68             set
69             {
70                   if (index >= 0 && index <= name_list.Length - 1)
71                   {
72                       name_list[index] = value;
73                   }
74             }
75         }       
76     }
77 }

posted @ 2016-03-21 17:10  C/C++/Python/Java  阅读(468)  评论(0编辑  收藏  举报