文章出處
文章列表
- 索引是一組get和set訪問器,類似于屬性的訪問器。
- 索引和屬性在很多方面是相似的。
- 和屬性一樣,索引不用分配內存來存儲;
- 索引和屬性都主要被用來訪問其他數據成員,這些成員和他們關聯,他們為這些成員提供設置和獲取訪問;
- 屬性通常表示單獨的數據成員;
- 索引通常表示多個數據成員;
- 可以把索引想象成提供獲取和設置類的多個數據成員的屬性,通過提供索引在許多可能的數據成員中進行選擇。索引本身可以是任何類型的,不僅僅是數值類型;
使用索引時,另外還有一些注意事項如下:
- 和屬性一樣,索引可以只有一個訪問器,也可以兩個都有;
- 索引總是實例成員。因此索引不能被聲明為static;
- 和屬性一樣,實現get和set訪問器的代碼,不一定要關聯到某個字段或者屬性。這段代碼可以做任何事情也可以什么都不做,只要get訪問器返回某個指定類型即可。
聲明索引:
聲明索引的語法如此下,請注意以下幾點:
- 索引沒有名稱,在名稱位置的是關鍵字this;
- 參數列表,在方括號中間;
- 參數列表中至少必須聲明一個參數。
聲明索引類似于聲明屬性。下圖有他們的相同點和不同點:
索引的set訪問器:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { public class Employee { public string FirstName; public string Lastname; public string CityOfBirth; /// <summary> /// 創建索引 /// </summary> /// <param name="index"></param> /// <returns></returns> public string this[int index] { set { switch (index) { case 0: FirstName = value; break; case 1: Lastname = value; break; case 2: CityOfBirth = value; break; default: throw new ArgumentOutOfRangeException("index"); } } get { switch (index) { case 0: return FirstName; case 1: return Lastname; case 2: return CityOfBirth; default: throw new ArgumentOutOfRangeException("index"); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 索引復習 { class Program { static void Main(string[] args) { Student stu = new Student() { firstName="c", lastName="b", cityOfBirth="w" }; //測試索引的訪問 Console.WriteLine("firstName={0}",stu[0]); Console.ReadKey(); } } }
文章列表
全站熱搜