C#索引属性用法实例分析
本文实例讲述了C#索引属性的用法。分享给大家供大家参考。具体如下:
这里演示C#类如何声明索引属性以表示不同种类事物的类似数组的集合。
//indexedproperty.cs
usingSystem;
publicclassDocument
{
//以下类型允许文档的查看方式与字的数组一样:
publicclassWordCollection
{
readonlyDocumentdocument;//包含文档
internalWordCollection(Documentd)
{
document=d;
}
//Helper函数--从字符“begin”开始在字符数组“text”中搜索
//字数“wordCount”。如果字数小于wordCount,
//则返回false。将“start”和
//“length”设置为单词在文本中的位置和长度:
privateboolGetWord(char[]text,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(text[i]);
if(inWord>=0)
{
if(!isLetter)
{
if(count++==wordCount)
{
start=inWord;
length=i-inWord;
returntrue;
}
inWord=-1;
}
}
else
{
if(isLetter)
inWord=i;
}
}
returnfalse;
}
//获取和设置包含文档中的字的索引器:
publicstringthis[intindex]
{
get
{
intstart,length;
if(GetWord(document.TextArray,0,index,outstart,outlength))
returnnewstring(document.TextArray,start,length);
else
thrownewIndexOutOfRangeException();
}
set
{
intstart,length;
if(GetWord(document.TextArray,0,index,outstart,outlength))
{
//用字符串“value”替换位于start/length处的
//字:
if(length==value.Length)
{
Array.Copy(value.ToCharArray(),0,document.TextArray,start,length);
}
else
{
char[]newText=
newchar[document.TextArray.Length+value.Length-length];
Array.Copy(document.TextArray,0,newText,0,start);
Array.Copy(value.ToCharArray(),0,newText,start,value.Length);
Array.Copy(document.TextArray,start+length,newText,start+value.Length,document.TextArray.Length-start-length);
document.TextArray=newText;
}
}
else
thrownewIndexOutOfRangeException();
}
}
//获取包含文档中字的计数:
publicintCount
{
get
{
intcount=0,start=0,length=0;
while(GetWord(document.TextArray,start+length,0,outstart,outlength))
++count;
returncount;
}
}
}
//以下类型允许文档的查看方式像字符的“数组”
//一样:
publicclassCharacterCollection
{
readonlyDocumentdocument;//包含文档
internalCharacterCollection(Documentd)
{
document=d;
}
//获取和设置包含文档中的字符的索引器:
publiccharthis[intindex]
{
get
{
returndocument.TextArray[index];
}
set
{
document.TextArray[index]=value;
}
}
//获取包含文档中字符的计数:
publicintCount
{
get
{
returndocument.TextArray.Length;
}
}
}
//由于字段的类型具有索引器,
//因此这些字段显示为“索引属性”:
publicWordCollectionWords;
publicCharacterCollectionCharacters;
privatechar[]TextArray;//文档的文本。
publicDocument(stringinitialText)
{
TextArray=initialText.ToCharArray();
Words=newWordCollection(this);
Characters=newCharacterCollection(this);
}
publicstringText
{
get
{
returnnewstring(TextArray);
}
}
}
classTest
{
staticvoidMain()
{
Documentd=newDocument(
"peterpiperpickedapeckofpickledpeppers.Howmanypickledpeppersdidpeterpiperpick?"
);
//将字“peter”更改为“penelope”:
for(inti=0;i<d.Words.Count;++i)
{
if(d.Words[i]=="peter")
d.Words[i]="penelope";
}
//将字符“p”更改为“P”
for(inti=0;i<d.Characters.Count;++i)
{
if(d.Characters[i]=='p')
d.Characters[i]='P';
}
Console.WriteLine(d.Text);
}
}
希望本文所述对大家的C#程序设计有所帮助。