?索引器是一組get和set訪問器,與屬性類似。如下展示了一個類的索引器的表現(xiàn)形式,該類可以回去和設置string型值。
string this[int index]{
set{
SetAccessorCode
}
get{
GetAccessorCode
}
}
索引器和屬性:
1.索引器和屬性一樣,索引器不用分配內(nèi)存來存儲。
2.索引器和屬性都主要用來訪問其他數(shù)據(jù)成員,它們與這些成員關(guān)聯(lián),并為它們提供獲取和設置訪問。
3.索引器總是實例成員,所以不能聲明為static。
聲明索引器:
1.索引器沒有名稱。在名稱的位置是關(guān)鍵字this。
2.參數(shù)列表在方括號中間。
3.參數(shù)列表中必須至少聲明一個參數(shù)。
ReturnType this [Type param1 ,...]{
get{}
set{}
}
例:
Class myclass{
public string lastname;
public string firstname;
public string cityofbirth;
public string this[int index]{
set{
switch (index){
case 0:lastname=value;
break;
case 1:firstname=value;
break;
case 2:cityofbirth=value;
break;
default:
throw new ArgumentOutOfRangeException("index");
}
get{
switch (index){
case 0: return lastname;
case 1: return firstname;
case 2: return cityofbirth;
default:
throw new ArgumentOutOfRangeException("index");
}
}
}
}
}