類索引器,可以使得你使用數組一樣的方式來訪問類的資料。
這種訪問多見於數組,列表,詞典,雜湊表的快捷訪問。
實際上寫法很簡單,寫成:public T1 this[T2 i]
代碼如下:
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Drawing;
6
7 namespace Indexer
8 {
9 public class Test
10 {
11 private List<string> _lstTest = new List<string>();
12
13 public List<string> Items
14 {
15 get { return _lstTest; }
16 set { _lstTest = value; }
17 }
18
19 public string this[int i]
20 {
21 get {
22 if ((i >= 0) && (i < _lstTest.Count)) return _lstTest[i];
23 else throw new IndexOutOfRangeException("the error index is " + i);
24 }
25
26 set {
27 if ((i >= 0) && (i < _lstTest.Count)) _lstTest[i] = value;
28 else throw new IndexOutOfRangeException("the error index is " + i);
29 }
30 }
31
32 public string this[string s] { get { return "Test Return " + s; } }
33
34
35 public string this[Color c] { get { return c.ToString(); } }
36 }
37
38
39 class Program
40 {
41 static void Main(string[] args)
42 {
43 Test test = new Test();
44
45 test.Items.Add("test1");
46 test.Items.Add("test2");
47 test.Items.Add("test3");
48 for (int i = 0; i < test.Items.Count; i++)
49 {
50 Console.WriteLine(test[i]);
51 }
52
53 Console.WriteLine("----------------------------------------------------------");
54 test[0] = "test4";
55 for (int i = 0; i < test.Items.Count; i++)
56 {
57 Console.WriteLine(test[i]);
58 }
59
60 Console.WriteLine("----------------------------------------------------------");
61 Console.WriteLine(test["香山飄雪"]);
62
63
64 Console.WriteLine("----------------------------------------------------------");
65 Console.WriteLine(test[Color.BlueViolet]);
66 }
67 }
68 }
很簡單吧,
第一個,我定義了一個可讀可寫的以int為參數的索引器。
第二個,我定義了一個可讀的以string為參數的索引器。
第三個,比較搞怪了,我定義了一個color參數的索引器。
呵呵,是很簡單吧!!
SkyDriver代碼下載:下載