c#教程第十一课:索引指示器
文章来源:互联网
本节课将介绍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 = "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); } } } |
说明 |
Indexer Output myInd[0]: empty myInd[1]: empty myInd[2]: empty myInd[3]: Another Value myInd[4]: empty myInd[5]: Any Value myInd[6]: empty myInd[7]: empty myInd[8]: empty myInd[9]: Some Value |
2.清单 11-2. 重载的索引指示器: OvrIndexer.cs |
using System; /// /// Implements overloaded indexers. /// class OvrIndexer { private string[] myData; private int arrSize; public OvrIndexer(int size) { arrSize = size; myData = new string[size]; for (int i="0"; i < size; i++) { myData = "empty"; } } public string this[int pos] { get { return myData[pos]; } set { myData[pos] = value; } } public string this[string data] { get { int count = 0; for (int i="0"; i < arrSize; i++) { if (myData == data) { count++; } } return count.ToString(); } set { for (int i="0"; i < arrSize; i++) { if (myData == data) { myData = value; } } } } static void Main(string[] args) { int size = 10; OvrIndexer myInd = new OvrIndexer(size); myInd[9] = "Some Value"; myInd[3] = "Another Value"; myInd[5] = "Any Value"; myInd["empty"] = "no value"; Console.WriteLine("\nIndexer Output\n"); for (int i="0"; i < size; i++) { Console.WriteLine("myInd[{0}]: {1}", i, myInd); } Console.WriteLine("\nNumber of \"no value\" entries: {0}", myInd["no value"]); } } |
说明 |
Indexer Output myInd[0]: no value myInd[1]: no value myInd[2]: no value myInd[3]: Another Value myInd[4]: no value myInd[5]: Any Value myInd[6]: no value myInd[7]: no value myInd[8]: no value myInd[9]: Some Value Number of "no value" entries: 7 |
public object this[int param1, ..., int paramN] { get { // process and return some class data } set { // process and assign some class data } } |
文章评论(0条评论)
登录后参与讨论