?索引器是一組get和set訪問器,與屬性類似厅瞎。如下展示了一個(gè)類的索引器的表現(xiàn)形式糖权,該類可以回去和設(shè)置string型值。
string this[int index]{
set{
SetAccessorCode
}
get{
GetAccessorCode
}
}
索引器和屬性:
1.索引器和屬性一樣企量,索引器不用分配內(nèi)存來存儲(chǔ)。
2.索引器和屬性都主要用來訪問其他數(shù)據(jù)成員亡电,它們與這些成員關(guān)聯(lián)届巩,并為它們提供獲取和設(shè)置訪問。
3.索引器總是實(shí)例成員份乒,所以不能聲明為static恕汇。
聲明索引器:
1.索引器沒有名稱。在名稱的位置是關(guān)鍵字this或辖。
2.參數(shù)列表在方括號(hào)中間瘾英。
3.參數(shù)列表中必須至少聲明一個(gè)參數(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");
}
}
}
}
}