16 Indexer

vencott·2021년 6월 2일
0

C#

목록 보기
16/32

배열처럼 인덱스([ ])를 써서 클래스 객체의 특정 필드 데이터에 엑세스

MyClass cls = new MyClass();
cls[0] = "First";

Indexer 정의

Indexer는 특별한 문법인 this[]를 써서 클래스 속성처럼 get과 set을 정의한다

클래스 디자인 시 클래스 내부의 어떤 데이터를 리턴하는지 정한다

리턴 데이터 타입도 여러가지로 지정 가능하다

입력 파라미터인 인덱스도 여러 데이터 타입을 쓸 수 있지만 주로 int나 string 타입을 사용하여 인덱스값을 주는 것이 일반적이다

class MyClass
{
   private const int MAX = 10;
   private string name;
   private int[] data = new int[MAX];

   // 인덱서 정의, int형 파라미터 사용
   public int this[int index] 
   {
      get
      {            
         if (index < 0 || index >= MAX)
         {
            throw new IndexOutOfRangeException();
         }
         else
         {
            return data[index];
         }
      }
      set
      {
         if (!(index < 0 || index >= MAX))
         {
            data[index] = value;
         }
      }
   }
}

class Program
{
   static void Main(string[] args)
   {
      MyClass cls = new MyClass();

      cls[1] = 1024; // get
      int i = cls[1]; // set
   }
}

출처: http://www.csharpstudy.com/

profile
Backend Developer

0개의 댓글