




下載本文檔
版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、(一)索引器教程定義索引器”使您可以創(chuàng)建作為康擬數(shù)組”的類。該類的實(shí)例可以使用口數(shù)組訪問(wèn)運(yùn)算符進(jìn)行訪問(wèn)。在C#中定義索引器類似于在C+中定義運(yùn)算符口,但前者靈活得多。對(duì)于封裝類似數(shù)組的功能或類似集合的功能的類,使用索引器使該類的用戶可以使用數(shù)組語(yǔ)法訪問(wèn)該類。例如,假定您想定義一個(gè)類,該類使文件顯示為字節(jié)數(shù)組。如果文件非常大,則將整個(gè)文件讀入內(nèi)存是不切實(shí)際的,尤其在您只想讀取或更改少數(shù)字節(jié)時(shí)。通過(guò)定義FileByteArray類,您可使文件外觀類似于字節(jié)數(shù)組,但讀或?qū)懽止?jié)時(shí),實(shí)際執(zhí)行的是文件的輸入和輸出。除下面的示例以外,本教程中還討論有關(guān)創(chuàng)建索引屬性”的高級(jí)主題。示例本示例中,F(xiàn)ileByte
2、Array類使得像字節(jié)數(shù)組那樣訪問(wèn)文件成為可能。Reverse類反轉(zhuǎn)文件的字節(jié)??梢赃\(yùn)行該程序以反轉(zhuǎn)任何文本文件的字節(jié),包括程序源文件本身。若要將反轉(zhuǎn)的文件更改回正常狀態(tài),請(qǐng)?jiān)谕晃募显俅芜\(yùn)行該程序。/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)若要測(cè)試程序,可使用具有以下內(nèi)容的文本文件(該文件在publicclassHellol(publicstaticvoidMain()(System.Console.WriteLine("Hello,World!");若要反轉(zhuǎn)該文件的字節(jié),請(qǐng)編譯程序,然后使用下面的命令行:indexerindexer.txt若要顯示反轉(zhuǎn)的文件,請(qǐng)輸入命令:Typeindexer.txt示例輸出;)"!dlroW,olleH"(eniLetirW.elosnoC.metsyS()(niaMdiovcitatscilbup(1olleHssalcci
8、lbup代碼討論* 由于索引器是使用口運(yùn)算符進(jìn)行訪問(wèn)的,因此沒(méi)有名稱。有關(guān)索引器聲明語(yǔ)法,請(qǐng)參見(jiàn)索引器。* 在上面的示例中,索引器類型是byte,并采用long(64位整數(shù))類型的單個(gè)索引。獲取"(Get)訪問(wèn)器定義從文件讀取一個(gè)字節(jié)的代碼,而設(shè)置”(Set)訪問(wèn)器定義向文件寫(xiě)入一個(gè)字節(jié)的代碼。在設(shè)置”(Set)訪問(wèn)器內(nèi),預(yù)定義的參數(shù)值為正賦給虛擬數(shù)組元素的值。* 索引器必須至少有一個(gè)參數(shù)。盡管相當(dāng)少見(jiàn),但索引器可以有多個(gè)參數(shù),以模擬多維虛擬數(shù)組”。盡管整數(shù)參數(shù)最常見(jiàn),但索引器參數(shù)可以為任何類型。例如,標(biāo)準(zhǔn)的字典"(Dictionary)類提供參數(shù)類型為Object的索引器
9、。* 盡管索引器功能強(qiáng)大,但有一點(diǎn)很重要,僅當(dāng)類似數(shù)組的抽象化有意義時(shí)才使用索引器。始終應(yīng)仔細(xì)考慮使用常規(guī)方法是否會(huì)同樣清楚。例如,下面是使用索引器不當(dāng)?shù)睦樱篶lassEmployee(/VERYBADSTYLE:usinganindexertoaccess/thesalaryofanemployee.publicdoublethisintyear(get(/returnemployee'ssalaryforagivenyear.)盡管合法,但只有獲取"(Get)訪問(wèn)器的索引器通常不是很好的結(jié)構(gòu)。在此情況下,強(qiáng)烈建議考慮使用方法。(二)索引屬性本教程展示如何實(shí)現(xiàn)使用索引屬性
10、的類。索引屬性使您可以使用表示類似于數(shù)組的若干種不同事物的集合的類。學(xué)習(xí)本教程以前應(yīng)完成索引器教程。教程假定您要編寫(xiě)一個(gè)Document類,該類封裝非常長(zhǎng)的文本章節(jié)。為能夠方便地實(shí)現(xiàn)各種操作(如檢查拼寫(xiě)),您可能希望以單詞(以及字符)的虛擬數(shù)組形式查看文檔。下面的示例展示實(shí)現(xiàn)這種類的技術(shù)。對(duì)于每個(gè)索引屬性",您定義一個(gè)嵌套類,該類包含對(duì)主類實(shí)例的反向引用。主類上的readonly字段提供對(duì)嵌套類(定義每個(gè)虛擬數(shù)組)的實(shí)例的訪問(wèn)。每個(gè)嵌套類定義一個(gè)索引器以及其他類似集合的方法(例如Count屬性)。下面的示例針對(duì)Words”和Characters”展示這一點(diǎn)。注意:請(qǐng)慎重使用該技術(shù)!僅
11、在使用數(shù)組索引操作提供的抽象化能明確闡明使用您的類的代碼,并且索引器同時(shí)具有獲取"(Get)和設(shè)置"(Set)訪問(wèn)器時(shí),才使用該模式。示例本示例中定義了Document類。使用Words和Characters這兩個(gè)索引屬性在Document對(duì)象上執(zhí)行某些文本操作。/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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 供電產(chǎn)權(quán)分界協(xié)議書(shū)范本
- 高端別墅折疊門定制采購(gòu)合同模板
- 粵式茶餐廳區(qū)域加盟代理經(jīng)營(yíng)協(xié)議
- 精準(zhǔn)匹配車貸需求居間服務(wù)合同樣本
- 住宅小區(qū)拆遷補(bǔ)償及重建工程承包協(xié)議
- 采礦權(quán)抵押貸款合同范本及風(fēng)險(xiǎn)評(píng)估協(xié)議
- 節(jié)能減排教育實(shí)施路徑
- 電梯乘坐安全教育
- 余氯測(cè)定方法培訓(xùn)
- 智慧停車解決方案
- 2025年高考英語(yǔ)全國(guó)二卷試題含答案
- (正式版)HGT 22820-2024 化工安全儀表系統(tǒng)工程設(shè)計(jì)規(guī)范
- GB/T 213-2003煤的發(fā)熱量測(cè)定方法
- GB/T 19411-2003除濕機(jī)
- GB/T 15683-2008大米直鏈淀粉含量的測(cè)定
- 第3課 象外之境-中國(guó)傳統(tǒng)山水畫(huà) 說(shuō)課稿- 高中美術(shù)人教版(2019)美術(shù)鑒賞
- 幼兒園大班畢業(yè)典禮教師詩(shī)朗誦
- 【部編人教版】貴州省銅仁市2021-2022年八年級(jí)下期末數(shù)學(xué)試卷
- 礦用隔爆兼本安型電子皮帶秤技術(shù)規(guī)格書(shū)
- 冀教版七年級(jí)英語(yǔ)下冊(cè)期末試題-附答案
- 住所(經(jīng)營(yíng)場(chǎng)所)產(chǎn)權(quán)證明(模版)
評(píng)論
0/150
提交評(píng)論