C#索引器與索引屬性_第1頁
C#索引器與索引屬性_第2頁
C#索引器與索引屬性_第3頁
C#索引器與索引屬性_第4頁
C#索引器與索引屬性_第5頁
免費預覽已結束,剩余1頁可下載查看

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

1、(一)索引器教程定義索引器”使您可以創建作為康擬數組”的類。該類的實例可以使用口數組訪問運算符進行訪問。在C#中定義索引器類似于在C+中定義運算符口,但前者靈活得多。對于封裝類似數組的功能或類似集合的功能的類,使用索引器使該類的用戶可以使用數組語法訪問該類。例如,假定您想定義一個類,該類使文件顯示為字節數組。如果文件非常大,則將整個文件讀入內存是不切實際的,尤其在您只想讀取或更改少數字節時。通過定義FileByteArray類,您可使文件外觀類似于字節數組,但讀或寫字節時,實際執行的是文件的輸入和輸出。除下面的示例以外,本教程中還討論有關創建索引屬性”的高級主題。示例本示例中,FileByte

2、Array類使得像字節數組那樣訪問文件成為可能。Reverse類反轉文件的字節。可以運行該程序以反轉任何文本文件的字節,包括程序源文件本身。若要將反轉的文件更改回正常狀態,請在同一文件上再次運行該程序。/indexer.cs/arguments:indexer.txtusingSystem;usingSystem.IO;/Classtoprovideaccesstoalargefile/asifitwereabytearray.publicclassFileByteArrayStreamstream;/Holdstheunderlyingstream/usedtoaccessthefile./

3、CreateanewFileByteArrayencapsulatingaparticularfile.publicFileByteArray(stringfileName)stream=newFileStream(fileName,FileMode.Open);/Closethestream.Thisshouldbethelastthingdone/whenyouarefinished.publicvoidClose()stream.Close();stream=null;/Indexertoprovideread/writeaccesstothefile.publicbytethislon

4、gindex/longisa64-bitinteger/Readonebyteatoffsetindexandreturnit.getbytebuffer=newbyte1;stream.Seek(index,SeekOrigin.Begin);stream.Read(buffer,0,1);returnbuffer0;/Writeonebyteatoffsetindexandreturnit.setbytebuffer=newbyte1value;stream.Seek(index,SeekOrigin.Begin);stream.Write(buffer,0,1);/Getthetotal

5、lengthofthefile.publiclongLengthgetreturnstream.Seek(0,SeekOrigin.End);/DemonstratetheFileByteArrayclass./Reversesthebytesinafile.publicclassReversepublicstaticvoidMain(Stringargs)/Checkforarguments.if(args.Length=0)Console.WriteLine("indexer<filename>");return;FileByteArrayfile=newF

6、ileByteArray(args0);longlen=file.Length;/Swapbytesinthefiletoreverseit.for(longi=0;i<len/2;+i)bytet;/Notethatindexingthe"file"variableinvokesthe/indexerontheFileByteStreamclass,whichreads/andwritesthebytesinthefile.t=filei;filei=filelen-i-1;filelen-i-1=t;file.Close();輸入:indexer.txt索引器”示

7、例中稱為Test.txt)若要測試程序,可使用具有以下內容的文本文件(該文件在publicclassHellol(publicstaticvoidMain()(System.Console.WriteLine("Hello,World!");若要反轉該文件的字節,請編譯程序,然后使用下面的命令行:indexerindexer.txt若要顯示反轉的文件,請輸入命令:Typeindexer.txt示例輸出;)"!dlroW,olleH"(eniLetirW.elosnoC.metsyS()(niaMdiovcitatscilbup(1olleHssalcci

8、lbup代碼討論* 由于索引器是使用口運算符進行訪問的,因此沒有名稱。有關索引器聲明語法,請參見索引器。* 在上面的示例中,索引器類型是byte,并采用long(64位整數)類型的單個索引。獲取"(Get)訪問器定義從文件讀取一個字節的代碼,而設置”(Set)訪問器定義向文件寫入一個字節的代碼。在設置”(Set)訪問器內,預定義的參數值為正賦給虛擬數組元素的值。* 索引器必須至少有一個參數。盡管相當少見,但索引器可以有多個參數,以模擬多維虛擬數組”。盡管整數參數最常見,但索引器參數可以為任何類型。例如,標準的字典"(Dictionary)類提供參數類型為Object的索引器

9、。* 盡管索引器功能強大,但有一點很重要,僅當類似數組的抽象化有意義時才使用索引器。始終應仔細考慮使用常規方法是否會同樣清楚。例如,下面是使用索引器不當的例子:classEmployee(/VERYBADSTYLE:usinganindexertoaccess/thesalaryofanemployee.publicdoublethisintyear(get(/returnemployee'ssalaryforagivenyear.)盡管合法,但只有獲取"(Get)訪問器的索引器通常不是很好的結構。在此情況下,強烈建議考慮使用方法。(二)索引屬性本教程展示如何實現使用索引屬性

10、的類。索引屬性使您可以使用表示類似于數組的若干種不同事物的集合的類。學習本教程以前應完成索引器教程。教程假定您要編寫一個Document類,該類封裝非常長的文本章節。為能夠方便地實現各種操作(如檢查拼寫),您可能希望以單詞(以及字符)的虛擬數組形式查看文檔。下面的示例展示實現這種類的技術。對于每個索引屬性",您定義一個嵌套類,該類包含對主類實例的反向引用。主類上的readonly字段提供對嵌套類(定義每個虛擬數組)的實例的訪問。每個嵌套類定義一個索引器以及其他類似集合的方法(例如Count屬性)。下面的示例針對Words”和Characters”展示這一點。注意:請慎重使用該技術!僅

11、在使用數組索引操作提供的抽象化能明確闡明使用您的類的代碼,并且索引器同時具有獲取"(Get)和設置"(Set)訪問器時,才使用該模式。示例本示例中定義了Document類。使用Words和Characters這兩個索引屬性在Document對象上執行某些文本操作。/indexedproperty.csusingSystem;publicclassDocument/Typeallowingthedocumenttobeviewedlikeanarrayofwords:publicclassWordCollectionreadonlyDocumentdocument;/Thec

12、ontainingdocumentinternalWordCollection(Documentd)document=d;)/Helperfunction-searchcharacterarray"text",startingat/character"begin",forwordnumber"wordCount."Returnsfalse/iftherearelessthanwordCountwords.Sets"start"and/length"tothepositionandlengthofthewo

13、rdwithintext:privateboolGetWord(chartext,intbegin,intwordCount,outintstart,outintlength)intend=text.Length;intcount=0;intinWord=-1;start=length=0;for(inti=begin;i<=end;+i)boolisLetter=i<end&&Char.IsLetterOrDigit(texti);if(inWord>=0)if(!isLetter)if(count+=wordCount)start=inWord;lengt

14、h=i-inWord;returntrue;inWord=-1;elseif(isLetter)inWord=i;returnfalse;/Indexertogetandsetwordsofthecontainingdocument:publicstringthisintindexgetintstart,length;if(GetWord(document.TextArray,0,index,outstart,outlength)returnnewstring(document.TextArray,start,length);elsethrownewIndexOutOfRangeExcepti

15、on();setintstart,length;if(GetWord(document.TextArray,0,index,outstart,outlength)/Replacethewordatstart/lengthwiththe/string"value":if(length=value.Length)Array.Copy(value.ToCharArray(),0,document.TextArray,start,length);)else(char口newText=newchardocument.TextArray.Length+value.Length-leng

16、th;Array.Copy(document.TextArray,0,newText,0,start);Array.Copy(value.ToCharArray(),0,newText,start,value.Length);Array.Copy(document.TextArray,start+lengthnewText,start+value.Length,document.TextArray.Length-start-length);document.TextArray=newText;)elsethrownewIndexOutOfRangeException();)/Getthecou

17、ntofwordsinthecontainingdocument:publicintCount(get(0,intcount=0,start=0,length=0;while(GetWord(document.TextArray,start+length,outstart,outlength)+count;returncount;)/Typeallowingthedocumenttobeviewedlikean"array"/ofcharacters:publicclassCharacterCollection(readonlyDocumentdocument;/Theco

18、ntainingdocumentinternalCharacterCollection(Documentd)(document=d;)/Indexertogetandsetcharactersinthecontainingdocument:publiccharthisintindex(get(returndocument.TextArrayindex;set(document.TextArrayindex=value)/Getthecountofcharactersinthecontainingdocument:publicintCount(get(returndocument.TextArray.Length;)/Becausethetypesofthefieldshaveindexers,/thesefieldsappearas"indexedpr

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論