本节课将介绍C#的索引指示器,其目的包括: 1.了解什么是索引指示器
2.如何实现索引指示器
3.重载索引指示器
4.了解如何实现多参数的索引指示器
索引指示器并不难使用。它们的用法跟数组相同。在一个类内部,你可以按照你的意愿来管理一组数据的集合。这些对象可以是类成员的有限集合,也可以是另外一个数组,或者是一些复杂的数据结构。不考虑类的内部实现,其数据可以通过使用索引指示器来获得。如下是一个例子:
1.清单 11-1. 索引指示器的例子:IntIndexer.cs |
using System; /// /// A simple indexer example. /// class IntIndexer { private string[] myData;
public IntIndexer(int size) { myData = new string[size]; for (int i=0; i < size; i++) { myData[i] = "empty"; } } public string this[int pos] { get { return myData[pos]; } set { myData[pos] = value; } }
static void Main(string[] args) { int size = 10; IntIndexer myInd = new IntIndexer(size); myInd[9] = "Some Value"; myInd[3] = "Another Value"; myInd[5] = "Any Value"; Console.WriteLine("/nIndexer Output/n"); for (int i=0; i < size; i++) { Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]); } } } |
<  
1/2 1 2 下一页 尾页 |