C# 索引器

  1. 属性与索引的区别
    属性 索引器
     通过名称标识  通过参数列表进行标识
     通过简单名称访问  通过[]运算符访问
     可以用static修饰  不能用static修饰
     get访问器没有参数  get访问器具有与索引相同的参数列表
     set访问器包含隐式value参数  除了value参数外,索引的set访问器还有与索引相同的参数列表
  2.  示例
 1 class Person
 2     {
 3         private readonly string[] _data = new string[6];
 4         private readonly string[] _keys = {
 5         "Name", "Age", "Sex"
 6         };
 7 
 8         //注:程序中用了两种方法来索引:
 9         //一是整数作下标,二是字符串(关键词名)作下标
10         public string this[int idx]
11         {
12             set
13             {
14                 if (idx >= 0 && idx < _data.Length)
15                     _data[idx] = value;
16             }
17             get
18             {
19                 if (idx >= 0 && idx < _data.Length)
20                     return _data[idx];
21                 return null;
22             }
23         }
24         public string this[string key]
25         {
26             set
27             {
28                 int idx = FindKey(key);
29                 this[idx] = value;
30             }
31             get
32             {
33                 return this[FindKey(key)];
34             }
35         }
36         private int FindKey(string key)
37         {
38             for (int i = 0; i < _keys.Length; i++)
39                 if (_keys[i] == key) return i;
40             return -1;
41         }
42         static void Main(string[] args)
43         {
44             Person record = new Person();
45             record[0] = "Jhon Snow";
46             record[1] = "23";
47             record["Sex"] = "";
48             Console.WriteLine(record["Name"]);
49             Console.WriteLine(record["Age"]);
50             Console.WriteLine(record[2]);
51             Console.ReadLine();
52         }
53     }

 

posted @ 2015-07-12 15:34  David Huang  阅读(235)  评论(0编辑  收藏  举报