C# 程序員參考--索引器教程

發表于:2007-07-14來源:作者:點擊數: 標簽:
C# 程序員 參考--索引器教程: 本教程展示 C# 類如何聲明索引器以提供對類的類似數組的訪問。 示例文件 請參見“索引器”示例以下載和生成本教程中討論的示例文件。 教程 定義“索引器”使您可以創建作為“虛擬數組”的類。該類的實例可以使用 [] 數組訪問運
C# 程序員參考--索引器教程:

本教程展示 C# 類如何聲明索引器以提供對類的類似數組的訪問。

示例文件

請參見“索引器”示例以下載和生成本教程中討論的示例文件。

教程

定義“索引器”使您可以創建作為“虛擬數組”的類。該類的實例可以使用 [] 數組訪問運算符進行訪問。在 C# 中定義索引器類似于在 C++ 中定義運算符 [],但前者靈活得多。對于封裝類似數組的功能或類似集合的功能的類,使用索引器使該類的用戶可以使用數組語法訪問該類。

例如,假定您想定義一個類,該類使文件顯示為字節數組。如果文件非常大,則將整個文件讀入內存是不切實際的,尤其在您只想讀取或更改少數字節時。通過定義 FileByteArray 類,您可使文件外觀類似于字節數組,但讀或寫字節時,實際執行的是文件的輸入和輸出。

除下面的示例以外,本教程中還討論有關“創建索引屬性”的高級主題。

示例

本示例中,FileByteArray 類使得像字節數組那樣訪問文件成為可能。Reverse 類反轉文件的字節??梢赃\行該程序以反轉任何文本文件的字節,包括程序源文件本身。若要將反轉的文件更改回正常狀態,請在同一文件上再次運行該程序。

// indexer.cs// arguments: indexer.txtusing System;using System.IO;// Class to provide aclearcase/" target="_blank" >ccess 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();    } }

輸入:indexer.txt

若要測試程序,可使用具有以下內容的文本文件(該文件在“索引器”示例中稱為 Test.txt)。

public class Hello1{   public static void Main()   {      System.Console.WriteLine("Hello, World!");   }}

若要反轉該文件的字節,請編譯程序,然后使用下面的命令行:

indexer indexer.txt

若要顯示反轉的文件,請輸入命令:

Type indexer.txt

示例輸出

}};)"!dlroW ,olleH"(eniLetirW.elosnoC.metsyS{)(niaM diov citats cilbup{1olleH ssalc cilbup

代碼討論

  • 由于索引器是使用 [] 運算符進行訪問的,因此沒有名稱。有關索引器聲明語法,請參見索引器。
  • 在上面的示例中,索引器類型是 byte,并采用 long(64 位整數)類型的單個索引?!矮@取”(Get) 訪問器定義從文件讀取一個字節的代碼,而“設置”(Set) 訪問器定義向文件寫入一個字節的代碼。在“設置”(Set) 訪問器內,預定義的參數值為正賦給虛擬數組元素的值。
  • 索引器必須至少有一個參數。盡管相當少見,但索引器可以有多個參數,以模擬多維“虛擬數組”。盡管整數參數最常見,但索引器參數可以為任何類型。例如,標準的“字典”(Dictionary) 類提供參數類型為 Object 的索引器。
  • 盡管索引器功能強大,但有一點很重要,僅當類似數組的抽象化有意義時才使用索引器。始終應仔細考慮使用常規方法是否會同樣清楚。例如,下面是使用索引器不當的例子:
    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) 訪問器的索引器通常不是很好的結構。在此情況下,強烈建議考慮使用方法。

  • 索引器可以重載(有關更多信息,請參見 10.8.1 索引器重載)。

原文轉自:http://www.anti-gravitydesign.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97