利用索引器,我们可以象使用数组一样对类,结构,和接口编制索引。在类和结构上定义索引器,需要使用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;
- }
- }
- }
- }