索引器允许类或结构的实例按照与数组相同的方式进行索引。要声明类或结构上的索引器,请使用this关键字,例如:
代码
1 class SampleCollection<T>
2 {
3 private T[] arr = new T[100];
4 public T this[int i]
5 {
6 get { return arr[i]; }
7 set { arr[i] = value; }
8 }
9 }
10
11 class Program
12 {
13 static void Main(string[] args)
14 {
15 SampleCollection<string> s = new SampleCollection<string>();
16 s[0] = "索引器的使用";
17 s[1] = "fff";
18 System.Console.WriteLine(s[0]);
19 System.Console.WriteLine(s[1]);
20 Console.Read();
21 }
22 }

浙公网安备 33010602011771号