索引器的应用

来源:互联网 发布:12306抢票软件 编辑:程序博客网 时间:2024/05/16 16:14

    利用索引器,我们可以象使用数组一样对类,结构,和接口编制索引。在类和结构上定义索引器,需要使用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. }
原创粉丝点击