2015년 9월 14일 월요일

인덱서

참조 : http://blanedil.tistory.com/12
참조 : http://www.devpia.com/Maeul/Contents/Detail.aspx?BoardID=17&MaeulNo=8&no=55680&ref=55672

1. 배열 연산자인 '[]'를 통해서 객체를 다룰 수 있도록 해주는 특별한 형태의 프로퍼티이다.
프로퍼티 이름 대신에 지정어 this를 사용한다.
2. 구조는 프로퍼티와 유사하며 get /set 접근자를 사용한다.
3. 객체를 인덱싱 하기 위한 index 인자를 가진다.
4. 이름 자체를 배열로 이용하기 떄문에 this 키워드가 인덱스의 이름으로 사용된다.

using System;
class IndexerClass
{
   private int [] myArray = new int[100];
   public int this [int index]   // Indexer declaration
   {
      get
      {
         // Check the index limits.
         if (index < 0 || index >= 100)
            return 0;
         else
            return myArray[index];
      }
      set
      {
         if (!(index < 0 || index >= 100))
            myArray[index] = value;
      }
   }
}

public class MainClass
{
   public static void Main()
   {
      IndexerClass b = new IndexerClass();
      // Call the indexer to initialize the elements #3 and #5.
      b[3] = 256;
      b[5] = 1024;
      for (int i=0; i<=10; i++)
      {
         Console.WriteLine("Element #{0} = {1}", i, b[i]);
      }
   }
}

댓글 없음:

댓글 쓰기