Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

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