什麼是 C# 中的過載索引器?


C# 中的索引器允許對物件進行索引編制,就像陣列一樣。當定義類的索引器時,該類的行為類似於虛擬陣列。然後,你可以使用陣列訪問運算子 ([ ]) 訪問該類的例項。

可以過載索引器。還可以在索引器中使用多個引數,且每個引數的型別可能不同。

以下是 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] = "John";
         names[1] = "Joe";
         names[2] = "Graham";
         names[3] = "William";
         names[4] = "Jack";
         names[5] = "Tom";
         names[6] = "Tim";
         //using the first indexer with int parameter
         for (int i = 0; i < IndexedNames.size; i++) {
            Console.WriteLine(names[i]);
         }
         //using the second indexer with the string parameter
         Console.WriteLine(names["Nuha"]);
         Console.ReadKey();
      }  
   }
}

輸出

John
Joe
Graham
William
Jack
Tom
Tim
N. A.
N. A.
N. A.
10

更新日期: 20-Jun-2020

596 次瀏覽

開啟您的職業

完成課程並獲得認證

開始
廣告
© . All rights reserved.