C#索引器(一)
索引器允許類和結構的實例按照與數組相同的方式進行索引,索引器類似與屬性,不同之處在于他們的訪問器采用參數。被稱為有參屬性。
簡單的索引器實例:
class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? IndexClass a = new IndexClass();
??????????? a[0] = "張三";
??????????? a[1] = "李四";
??????????? a[2] = "王五";
??????????? Console.WriteLine("a[0]=" + a[0]);
??????????? Console.WriteLine("a[1]=" + a[1]);
??????????? Console.WriteLine("a[2]=" + a[2]);
??????????? Console.ReadKey();
??????? }
??? }
??? class IndexClass
??? {
??????? private string[] name = new string[10];
??????? public string this[int index]
??????? {
??????????? get { return name[index]; }
??????????? set { this.name[index] = value; }
??????? }
??? }
索引器與數組的比較:
索引器的索引值不受類型限制。用來訪問數組的索引值一定是整數,而索引器可以是其他類型的索引值。
索引器允許重載,一個類可以有多個索引器。
索引器不是一個變量沒有直接對應的數據存儲地方。索引器有get和set訪問器。
轉載于:https://www.cnblogs.com/jiang_jiajia10/archive/2009/03/13/1410771.html
總結
- 上一篇: TCP 端口监听队列原理
- 下一篇: c# char unsigned_dll