[C# 객체지향] 멤버 유형 확장3_인덱서(indexer)

eunjin lee·2022년 7월 26일
0

C# 9.0 프로그래밍

목록 보기
17/50

array[0]과 같이 배열의 요소에 접근할 때 쓰이는 [] 연산자는 사용자가 직접 정의할 수 없다. 이를 보완하기 위해 c#에서는 this 예약어를 이용한 인덱서 구문을 제공한다.


✅ 샘플 코드

    class Test
    {
        static void Main(string[] args)
        {
            IntegerText number = new IntegerText(1234567890);
            Console.WriteLine("뒤에서 첫 번째 : "+number[0]);
            Console.WriteLine("뒤에서 세 번째 : "+number[2]);
            Console.WriteLine("뒤에서 열 번째 : "+number[9]);
        }
    }

    class IntegerText
    {
        char[] textNumArray;
        public IntegerText(int number)
        {
            textNumArray = number.ToString().ToCharArray();
        }

        public char this[int index]
        {
            get 
            { 
                return textNumArray[textNumArray.Length - index - 1]; 
            }
            set
            {
                textNumArray[textNumArray.Length - index - 1] = value;
            }
        }

    }

✅ 결과

뒤에서 첫 번째 : 0
뒤에서 세 번째 : 8
뒤에서 열 번째 : 1

0개의 댓글