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-06-2020

596 次瀏覽

開始你的職業生涯

完成課程並獲取認證

開始
廣告
© . All rights reserved.