利用索引器,我們可以象使用數組一樣對類,結構,和介面編製索引。在類和結構上定義索引器,需要使用this關鍵字。
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace ConsoleTest
- {
- class mainClass
- {
- static void Main()
- {
- IndexerDemo demo = new IndexerDemo();
- int result=demo[3];
- Console.WriteLine(result); //Output 67
- }
- }
- class IndexerDemo
- {
- private int[] arrs = new int[] { 5, 8, 54, 67, 25, 1 };
- public int this[int index]
- {
- get
- {
- return arrs[index];
- }
- }
- }
- }
除了使用索引器時,需要使用參數,其餘特性和屬性相似。
注意:
1.使用索引器,可以象使用數組一樣操作類,結構和介面
2.不一定要用整數索引
3.可以多載
4.可以多參
參考msdn.
利用索引器實現一個簡單的集合類
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Collections;
- namespace Demo
- {
- class Demo3
- {
- static void Main()
- {
-
- MyArray arr = new MyArray();
- arr.Add("Hello");
- arr.Add("world");
- arr.Add("net");
- for (int i = 0; i < arr.Length; i++)
- {
- Console.WriteLine(arr[i]);
- }
- }
- }
- class MyArray
- {
- private string[] _items=new string[5];
- private int _size = 0;
- public void Add(string item)
- {
- _items[_size] = item;
- _size++;
- }
- public string this[int index]
- {
- get
- {
- return _items[index];
- }
- }
- public int Length
- {
- get
- {
- return _size;
- }
- }
- }
- }