本教程展示 C# 類如何聲明索引器以提供對類的類似數組的訪問。
請參見“索引器”示例以下載和生成本教程中討論的示例文件。
定義“索引器”使您可以創建作為“虛擬數組”的類。該類的實例可以使用 [] 數組訪問運算符進行訪問。在 C# 中定義索引器類似於在 C++ 中定義運算符 [],但前者靈活得多。對於封裝類似數組的功能或類似集合的功能的類,使用索引器使該類的用戶可以使用數組語法訪問該類。
例如,假定您想定義一個類,該類使文件顯示為字節數組。如果文件非常大,則將整個文件讀入內存是不切實際的,尤其在您只想讀取或更改少數字節時。通過定義 FileByteArray 類,您可使文件外觀類似於字節數組,但讀或寫字節時,實際執行的是文件的輸入和輸出。
除下面的示例以外,本教程中還討論有關“創建索引屬性”的高級主題。
本示例中,FileByteArray 類使得像字節數組那樣訪問文件成為可能。Reverse 類反轉文件的字節。可以運行該程序以反轉任何文本文件的字節,包括程序源文件本身。若要將反轉的文件更改回正常狀態,請在同一文件上再次運行該程序。
// indexer.cs
// arguments: indexer.txt
using System;
using System.IO;
// Class to provide access to a large file
// as if it were a byte array.
public class FileByteArray
{
Stream stream; // Holds the underlying stream
// used to access the file.
// Create a new FileByteArray encapsulating a particular file.
public FileByteArray(string fileName)
{
stream = new FileStream(fileName, FileMode.Open);
}
// Close the stream. This should be the last thing done
// when you are finished.
public void Close()
{
stream.Close();
stream = null;
}
// Indexer to provide read/write access to the file.
public byte this[long index] // long is a 64-bit integer
{
// Read one byte at offset index and return it.
get
{
byte[] buffer = new byte[1];
stream.Seek(index, SeekOrigin.Begin);
stream.Read(buffer, 0, 1);
return buffer[0];
}
// Write one byte at offset index and return it.
set
{
byte[] buffer = new byte[1] {value};
stream.Seek(index, SeekOrigin.Begin);
stream.Write(buffer, 0, 1);
}
}
// Get the total length of the file.
public long Length
{
get
{
return stream.Seek(0, SeekOrigin.End);
}
}
}
// Demonstrate the FileByteArray class.
// Reverses the bytes in a file.
public class Reverse
{
public static void Main(String[] args)
{
// Check for arguments.
if (args.Length == 0)
{
Console.WriteLine("indexer <filename>");
return;
}
FileByteArray file = new FileByteArray(args[0]);
long len = file.Length;
// Swap bytes in the file to reverse it.
for (long i = 0; i < len / 2; ++i)
{
byte t;
// Note that indexing the "file" variable invokes the
// indexer on the FileByteStream class, which reads
// and writes the bytes in the file.
t = file[i];
file[i] = file[len - i - 1];
file[len - i - 1] = t;
}
file.Close();
}
}
若要測試程序,可使用具有以下內容的文本文件(該文件在“索引器”示例中稱為 Test.txt)。
public class Hello1
{
public static void Main()
{
System.Console.WriteLine("Hello, World!");
}
}
若要反轉該文件的字節,請編譯程序,然後使用下面的命令行:
indexer indexer.txt
若要顯示反轉的文件,請輸入命令:
Type indexer.txt
}[1] [2] 下一頁
} ;)"!dlroW ,olleH"(eniLetirW.elosnoC.metsyS { )(niaM diov citats cilbup { 1olleH ssalc cilbup
class Employee
{
// VERY BAD STYLE: using an indexer to access
// the salary of an employee.
public double this[int year]
{
get
{
// return employee's salary for a given year.
}
}
}
盡管合法,但只有“獲取”(Get) 訪問器的索引器通常不是很好的結構。在此情況下,強烈建議考慮使用方法。
上一頁 [1] [2]