首页 > 代码库 > C#索引器

C#索引器

using System;  using System.Collections.Generic;  using System.Text;  namespace Index  {      class sample<T>  //这个类告诉我们如何使用客户端代码索引器      {          private T[] arr = new T[100];          public T this[int i] //索引器的签名由其形参的数量和类型组成。          {              get { return arr[i];}              set { arr[i] = value;}          }      }          class IndexerClass      {          private int[] arr = new int[100]; //定义数组          public int this[int index]   //索引器声明          {              get              {                  if (index < 0 || index >100)  return 0;                  return arr[index];              }              set              {                  if (!(index < 0 || index > 100))  arr[index] = value;               }          }      }      class String_index      {          string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };          private int GetDay(string testday)          {              int i = 0;              foreach(string day in days)              {                  if (day == testday)  return i;                  i++;              }              return -1;          }          public int this[string day]          {              get{ return GetDay(day); }          }      }      class Program      {          static void Main(string[] args)          {              sample<string> string_value = http://www.mamicode.com/new sample<string>();              string_value[0] = "Hello world";              System.Console.WriteLine(string_value[0]);                IndexerClass test = new IndexerClass();              //调用索引器初始化第2、4个数据              test[3] = 123;              test[5] = 1024;              for (int i = 0; i <= 10; i++ )              { System.Console.WriteLine("数据为#{0} = {1}", i, test[i]);}              String_index week = new String_index();              System.Console.WriteLine("这是一周的第{0}天", week["Tues"]);              Console.ReadKey();          }      }  }  

来源:http://blog.csdn.net/seawaywjd/article/details/7061155

C#索引器