索引器(Indexer)是C#引入的一個新型的類成員,它使得類中的對象可以像數組那樣方便、直觀的被引用。索引器非常類似于屬性,但索引器可以有參數列表,且只能作用在實例對象上,而不能在類上直接作用。定義了索引器的類可以讓您像訪問數組一樣的使用 [ ] 運算符訪問類的成員。(當然高級的應用還有很多,比如說可以把數組通過索引器映射出去等等)
索引器的語法:
public class Indexsy { PRivate string[] array ; public Indexsy(int num) { array = new string[num]; for (int i = 0; i < num; i++) { array[i] = "Array"+i; } } public string this[int num] { get { return array[num]; } set { array[num] = value; } } }///索引器調用 Indexsy sy = new Indexsy(10); Response.Write(sy[5]);//輸出Array5多參數的實例
public class Indexsy { private string[] array ; public Indexsy(int num) { array = new string[num]; for (int i = 0; i < num; i++) { array[i] = "Array"+i; } } public string this[int num, string con] { get { if (num == 6) { return con; } else { return array[num]; } } set { if (num == 6) { array[num] = con; } else { array[num] = value; } } } }//方法調用 Indexsy sy = new Indexsy(10); sy[5,"10"] = "更換set值"; Response.Write(sy[5,""]+" "+sy[6,"更換內部參數"]+" "+sy[8,""]);//輸出為更換set值 更換內部參數 Array8,
索引器和數組比較:
(1)索引器的索引值(Index)類型不受限制
(2)索引器允許重載
(3)索引器不是一個變量
索引器和屬性的不同點
(1)屬性以名稱來標識,索引器以函數形式標識
(2)索引器可以被重載,屬性不可以
(3)索引器不能聲明為static,屬性可以
新聞熱點
疑難解答