C#索引器的使用

來源:互聯網
上載者:User

索引器這個東東,我也是最近才接觸,一般所說的索引器,是指定義在某個類裡面的一個類似屬性的東西。索引器是.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();
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.