1. 程式人生 > >C# 索引器(Indexer)

C# 索引器(Indexer)

索引器(Indexer) 允許一個物件可以像陣列一樣被索引。當您為類定義一個索引器時,該類的行為就會像一個 虛擬陣列(virtual array) 一樣。您可以使用陣列訪問運算子([ ])來訪問該類的例項。

語法

一維索引器的語法如下:

element-type this[int index] 
{
   // get 訪問器
   get 
   {
      // 返回 index 指定的值
   }

   // set 訪問器
   set 
   {
      // 設定 index 指定的值 
   }
}

索引器(Indexer)的用途

索引器的行為的宣告在某種程度上類似於屬性(property)。就像屬性(property),您可使用 get

 和 set 訪問器來定義索引器。但是,屬性返回或設定一個特定的資料成員,而索引器返回或設定物件例項的一個特定值。換句話說,它把例項資料分為更小的部分,並索引每個部分,獲取或設定每個部分。

定義一個屬性(property)包括提供屬性名稱。索引器定義的時候不帶有名稱,但帶有 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;
            }
         }
      }

      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();
      }
   }
}

當上面的程式碼被編譯和執行時,它會產生下列結果:

Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.

過載索引器(Indexer)

索引器(Indexer)可被過載。索引器宣告的時候也可帶有多個引數,且每個引數可以是不同的型別。沒有必要讓索引器必須是整型的。C# 允許索引器可以是其他型別,例如,字串型別。

下面的例項演示了過載索引器:

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";
         // 使用帶有 int 引數的第一個索引器
         for (int i = 0; i < IndexedNames.size; i++)
         {
            Console.WriteLine(names[i]);
         }
         // 使用帶有 string 引數的第二個索引器
         Console.WriteLine(names["Nuha"]);
         Console.ReadKey();
      }
   }
}

當上面的程式碼被編譯和執行時,它會產生下列結果:

Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
2

 C# 屬性(Property)

C# 委託(Delegate) 

 

2 篇筆記 寫筆記

  1.    Yorkove

      arl***[email protected]

    也可在 class 例項化時自定義索引器 size。

    例項:

    public class IndexedNames
    {
      private string[] nameList;
      public int size;
      public IndexedNames(int size)
      {
        this.size = size;
        nameList = new string[size];
        for(int i = 0;i < size; i++)
        {
          nameList[i]="N. A.";
        }
      }
      publis string this[int index]
      {
        get
        {
          string temp;
          if(index>=0 && index<size)
          {
            temp = nameList[index];
          }
          else
          {
            temp = "";
          }
          return temp;
        }
        set
        {
          if(index>=0 && index<size)
          {
            nameList[index] = value;
          }
        }
      }
    }
    static void Main(string[] args)
    {
       IndexedNames index = new IndexedNames(5);
       index[0] = "Zara";
       index[1] = "Riz";
       index[2] = "Nuha";
       index[3] = "Asif";
       index[4] = "Davinder";
       for (int i = 0; i < index.size; i++)
       {
          Console.WriteLine(index[i]);
       }
       Console.ReadKey();
    }
    Yorkove

       Yorkove

      arl***[email protected]

    5個月前 (07-24)
  2.    二狗子

      137***[email protected]

    using System;
    
    namespace IndexerApplication{
        //1.類成員變數是陣列的情況
        // 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;
                    // }
                // }
            // }
            
            // 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]);
                // }
            // }
        // }
        
            //2.類成員變數是多個基本型別
        class Employee{
            public string firstName;
            public string middleName;
            public string lastName;
            
            public string this[string index]{
                set{
                    switch(index){
                        case "a":firstName = value;
                            break;
                        case "b":middleName = value;
                            break;
                        case "c":lastName = value;
                            break;
                        default: throw new ArgumentOutOfRangeException("index");
                    }
                }
                get{
                    switch(index){
                        case "a":return firstName;
                        case "b":return middleName;
                        case "c":return lastName;
                        default: throw new ArgumentOutOfRangeException("index");
                    }
                }
            }
            
            static void Main(string[] args){
                Employee ee = new Employee();
                
                ee.firstName = "胡";
                ee.middleName = "大";
                ee.lastName = "陽";
                
                Console.WriteLine("我的名字叫: {0}{1}{2}",ee["a"],ee["b"],ee["c"]);
            }
        }
    }

from:http://www.runoob.com/csharp/csharp-indexer.html