索引器的應用

來源:互聯網
上載者:User

    利用索引器,我們可以象使用數組一樣對類,結構,和介面編製索引。在類和結構上定義索引器,需要使用this關鍵字。

 

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace ConsoleTest
  5. {
  6.     class mainClass
  7.     {
  8.         static void Main()
  9.         {
  10.             IndexerDemo demo = new IndexerDemo();
  11.             int result=demo[3];
  12.             Console.WriteLine(result); //Output 67
  13.         }
  14.     }
  15.     class IndexerDemo
  16.     {
  17.         private int[] arrs = new int[] { 5, 8, 54, 67, 25, 1 };
  18.         public int this[int index]
  19.         {
  20.             get 
  21.             {
  22.                 return arrs[index];
  23.             }
  24.         }
  25.     }
  26. }

    除了使用索引器時,需要使用參數,其餘特性和屬性相似。

    注意:
    1.使用索引器,可以象使用數組一樣操作類,結構和介面

    2.不一定要用整數索引

    3.可以多載

    4.可以多參

參考msdn.

利用索引器實現一個簡單的集合類

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Collections;
  5. namespace Demo
  6. {
  7.     class Demo3
  8.     {
  9.         static void Main()
  10.         {
  11.            
  12.             MyArray arr = new MyArray();
  13.             arr.Add("Hello");
  14.             arr.Add("world");
  15.             arr.Add("net");
  16.             for (int i = 0; i < arr.Length; i++)
  17.             {
  18.                 Console.WriteLine(arr[i]);
  19.             }
  20.         }
  21.     }
  22.     class MyArray
  23.     {
  24.         private string[] _items=new string[5];
  25.         private int _size = 0;
  26.         public void Add(string item)
  27.         {
  28.             _items[_size] = item;
  29.             _size++;
  30.         }
  31.         public string this[int index]
  32.         {
  33.             get
  34.             {
  35.                 return _items[index];
  36.             }
  37.         }
  38.         public int Length
  39.         {
  40.             get
  41.             {
  42.                 return _size;
  43.             }
  44.         }
  45.     }    
  46. }

聯繫我們

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