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

C#의 인덱서는 무엇입니까?

<시간/>

인덱서를 사용하면 배열과 같은 개체를 인덱싱할 수 있습니다.

구문을 보자 -

element-type this[int index] {
   // The get accessor.
   get {
      // return the value specified by index
   }
   // The set accessor.
   set {
      // set the value specified by index
   }
}

다음은 C#에서 인덱서를 구현하는 방법을 보여주는 예입니다 -

예시

using System;
namespace Demo {
   class Program {
      private string[] namelist = new string[size];
      static public int size = 10;
      public Program() {
         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) {
         Program names = new Program();
         names[0] = "Tom";
         names[1] = "Jacob";
         names[2] = "Jack";
         names[3] = "Amy";
         names[4] = "Katy";
         names[5] = "Taylor";
         names[6] = "Brad";
         names[7] = "Scarlett";
         names[8] = "James";
         for ( int i = 0; i < Program.size; i++ ) {
            Console.WriteLine(names[i]);
         }
         Console.ReadKey();
      }
   }
}

출력

Tom
Jacob
Jack
Amy
Katy
Taylor
Brad
Scarlett
James
N. A.