C#编程-97:索引器在类中的使用_彭世瑜_新浪博客

106 阅读1分钟
  1. using System;

  2. using System.Collections.Generic;

  3. using System.Linq;

  4. using System.Text;

  5.  

  6. namespace ClassIndexTest

  7. {

  8.     class IndexTest

  9.     {

  10.         private int[] myint = new int[10];

  11.  

  12.         public int this[int index]

  13.         {

  14.             get { 

  15.             if(index>=0 && index<=9) return myint[index];

  16.             else

  17.                 return 0;

  18.             }

  19.             set {

  20.                 if (index >= 0 && index <= 9) myint[index] = value;

  21.             }

  22.         }

  23.  

  24.     }

  25.     class WeekDay

  26.     {

  27.          private string[] weeks = { "星期一","星期二","星期三","星期四","星期五","星期六","星期日"};

  28.          private int GetDay(string weekday)

  29.          {

  30.              int i = 1;

  31.              foreach (string week in weeks)

  32.              {

  33.                  if (week == weekday) return i;

  34.                  i++;

  35.              }

  36.              return 0;       

  37.          }

  38.          public int this[string week]

  39.          {

  40.              get { return GetDay(week); }

  41.          }

  42.     }

  43.     class Program

  44.     {

  45.         static void Main(string[] args)

  46.         {

  47.             //访问类实例

  48.             IndexTest array = new IndexTest();

  49.             array[0] = 11;

  50.             array[-5] = 12;

  51.             array[3] = 14;

  52.             array[5] = 15;

  53.             array[11] = 16;

  54.             Console.WriteLine("array[0]={0}", array[0]);

  55.             Console.WriteLine("array[-5]={0}", array[-5]);

  56.             Console.WriteLine("array[3]={0}", array[3]);

  57.             Console.WriteLine("array[5]={0}", array[5]);

  58.             Console.WriteLine("array[11]={0}", array[11]);

  59.             Console.WriteLine("array[6]={0}", array[6]);

  60.  

  61.             //访问类成员

  62.             WeekDay weekday = new WeekDay();

  63.             Console.WriteLine(weekday["星期一"]);

  64.             Console.WriteLine(weekday["星期二"]);

  65.             Console.WriteLine(weekday["星期五"]);

  66.             Console.WriteLine(weekday["星期八"]);

  67.             Console.ReadKey();

  68.         }

  69.     }

  70. }

C#编程-97:索引器在类中的使用 C#编程-97:索引器在类中的使用

\