索引器這個東東,我也是最近才接觸,一般所說的索引器,是指定義在某個類裡面的一個類似屬性的東西。索引器是.net中新的類成員。類似與類的屬性。有些人乾脆稱呼它為帶參數的屬性。
索引器可以快速定位到類中某一個數群組成員的單元。下面看看代碼:
Indexer
class indexerClass
{
private int[] arr=new int[100];
private string[] names=new string[100];
public int this[int index]
{
get
{
if (index < 0 || index >= 100)
{
return -1;
}
else
{
return arr[index];
}
}
set//索引器的get,set被編譯器編譯成get_item,sge_item方法。
{
if (index >=0 && index < 100)
{
arr[index]=value;
}
}
}
public int this[string key]//索引器的參數也可是字串等,不一定只能是int
{
get
{
return GetNumber(key);
}
}
public int GetNumber(string Gender)
{
if (Gender == "boy")
{
return 1;
}
else if (Gender == "girl")
{
return 0;
}
else
{
return -1;
}
}
}
索引器參數大多是int類型,但也可以是其他類型,如string。
static void Main(string[] args)
{
indexerClass indexerTest = new indexerClass();
for (int i = 0; i < 10; i++)
{
indexerTest[i] = i + 2; //對類的對象,可以直接像運算元組一樣操作對象裡面的數組。
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine(indexerTest[i]);
}
Console.ReadKey();
}