日期:2012-07-19  浏览次数:20517 次

这一课讲述如何在C#的类中声明索引,以使类能象数组一样被访问,这样类的实例就能够使用
数组访问操作符[]来访问类对象.
在C#中定义索引和在C++中定义操作符[]类似.对于那些封装了数组或者使用起来有点象集合
的类,就可以使用索引,这样用户就能够使用访问数组的语法访问这个类.
举个例子,假定,你想要定义一个类,它使得文件就像一个字节数组一样.如果文件非常大,把
整个文件都读入内存是不切合实际的,尤其是在你只想读写其中一小部分字节的时候更是如
此.这里定义了一个类FileByteArray,使文件看起来就像一个数组一样,但是实际上只有在
字节读写的时候才会进行文件输入输出操作.

下面给出了如何定义一个索引属性.

例子

在这个例子中,FileByteArray使得对文件的访问像字节数组一样. Reverse类把文件的字节
颠倒过来.你可以就那下面这个程序本身试验一下,执行两次就恢复原状了.

000: // Indexers\indexer.cs
001: using System;
002: using System.IO;
003:
004: // Class to provide access to a large file
005: // as if it were a byte array.
006: public class FileByteArray
007: {
008:     Stream stream;      // Holds the underlying stream
009:                         // used to access the file.
010: // Create a new FileByteArray encapsulating a particular file.
011:     public FileByteArray(string fileName)
012:     {
013:         stream = new FileStream(fileName, FileMode.Open);
014:     }
015:
016:     // Close the stream. This should be the last thing done
017:     // when you are finished.
018:     public void Close()
019:     {
020:         stream.Close();
021:         stream = null;
022:     }
023:
024:     // Indexer to provide read/write access to the file.
025:     public byte this[long index]   // long is a 64-bit integer
026:     {
027:         // Read one byte at offset index and return it.
028:         get
029:         {
030:             byte[] buffer = new byte[1];
031:             stream.Seek(index, SeekOrigin.Begin);
032:             stream.Read(buffer, 0, 1);
033:             return buffer[0];
034:         }
035:         // Write one byte at offset index and return it.
036:         set
037:         {
038:             byte[] buffer = new byte[1] {value};
039:             stream.Seek(index, SeekOrigin.Begin);
040:             stream.Write(buffer, 0, 1);
041:         }
042:     }
043:
044:     // Get the total length of the file.
045:     public long Length
046:     {
047:         get {
048:             return stream.Seek(0, SeekOrigin.End);
049:         }
050:  &nbs