1. 程式人生 > >c#定義索引器

c#定義索引器

索引器的宣告在某種程度上類似於屬性的宣告,例如,使用 get 和 set 方法來定義一個索引器。不同的是,屬性值的定義要求返回或設定一個特定的資料成員,而索引器的定義要求返回或設定的是某個物件例項的一個值,即索引器將例項資料切分成許多部分,然後通過一些方法去索引、獲取或是設定每個部分。

定義屬性需要提供屬性名,而定義索引器需要提供一個指向物件例項的 this 關鍵字。

程式碼示例:

using System;
namespace IndexerApplication
{
   class IndexedNames
   {
      private string[] namelist = new string[size];
      static public int size = 10;
      public IndexedNames()
      {
         for (int i = 0; i < size; i++)
         namelist[i] = "N. A.";
      }
 
      public string this[int index]
      {
         get
         {
            string tmp;
 
            if( index >= 0 && index <= size-1 )
            {
               tmp = namelist[index];
            }
            else
            {
               tmp = "";
            }
 
            return ( tmp );
         }
         set
         {
            if( index >= 0 && index <= size-1 )
            {
               namelist[index] = value;
            }
         }
      }

     //索引器也可過載

    public int this[string name]
        {
            get
            {
                int index = 0;
                while (index < size)
                {
                    if (namelist[index] == name)
                    {
                        return index;
                    }
                    index++;
                }
                return index;
            }
        }


 
      static void Main(string[] args)
      {
         IndexedNames names = new IndexedNames();
         names[0] = "Zara";
         names[1] = "Riz";
         names[2] = "Nuha";
         names[3] = "Asif";
         names[4] = "Davinder";
         names[5] = "Sunil";
         names[6] = "Rubic";
         for ( int i = 0; i < IndexedNames.size; i++ )
         {
            Console.WriteLine(names[i]);
         }
 
         Console.ReadKey();
      }
   }
}