索引器
索引器能夠使物件像陣列一樣被索引,使用陣列的訪問方式 object[x]索引器的宣告在某種程度上類似于屬性的宣告,例如,使用 get 和 set 方法來定義一個索引器,不同的是,屬性值的定義要求回傳或設定一個特定的資料成員,而索引器的定義要求回傳或設定的是某個物件實體的一個值,即索引器將實體資料切分成許多部分,然后通過一些方法去索引、獲取或是設定每個部分,定義屬性需要提供屬性名,而定義索引器需要提供一個指向物件實體的 this 關鍵字,索引可以多載
使用索引示例:
using System; namespace IndexerApplication { class indexC { public static int number = 10; private string[] str = new string[number]; public indexC() { for(int i = 0; i < number; i++) { str[i] = "null"; } } public string this[int index] //創建索引,int為索引的型別 { set { if (index >= 0 && index < 10) { str[index] = value; //value為傳入字串 } } get { string temp=""; if (index >= 0 && index < 10) { temp = str[index]; } return temp; } } static void Main() { indexC I = new indexC(); I[0] = "zero"; I[1] = "one"; I[2] = "two"; for(int i = 0; i < indexC.number; i++) { Console.WriteLine(I[i]); } } } }
運行:
zero one two null null null null null null null C:\Program Files\dotnet\dotnet.exe (行程 5248)已退出,回傳代碼為: 0, 若要在除錯停止時自動關閉控制臺,請啟用“工具”->“選項”->“除錯”->“除錯停止時自動關閉控制臺”, 按任意鍵關閉此視窗...
參考鏈接:https://www.w3cschool.cn/wkcsharp/sozt1nvr.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/120905.html
標籤:C#
上一篇:C# yield checked,unchecked lock陳述句(C#學習筆記04)
下一篇:C# 求Π Π/4=1-1/3+1/5-1/7+......+1/(2*n-3)-1/(2*n-1); (n=2000)
