C#索引器(一)

來源:互聯網
上載者:User

索引器允許類和結構的執行個體按照與數組相同的方式進行索引,索引器類似與屬性,不同之處在於他們的訪問器採用參數。被稱為有參屬性。

簡單的索引器執行個體:

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訪問器。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.