인덱서(C# 프로그래밍 가이드)

인덱서를 사용하면 클래스 또는 구조체의 인스턴스를 배열과 마찬가지로 인덱싱할 수 있습니다. 인덱서는 접근자에 매개 변수가 있다는 것을 제외하면 속성과 비슷합니다.

다음 예제에서는 값을 할당하고 검색하기 위한 방법으로 간단한 getset 접근자 메서드를 사용하여 제네릭 클래스를 정의하고 제공합니다. Program 클래스는 문자열을 저장하기 위해 이 클래스의 인스턴스를 만듭니다.

class SampleCollection<T>
{
    // Declare an array to store the data elements.
    private T[] arr = new T[100];

    // Define the indexer, which will allow client code
    // to use [] notation on the class instance itself.
    // (See line 2 of code in Main below.)        
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets
            // the corresponding element from the internal array.
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer.
class Program
{
    static void Main(string[] args)
    {
        // Declare an instance of the SampleCollection type.
        SampleCollection<string> stringCollection = new SampleCollection<string>();

        // Use [] notation on the type.
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}

인덱서 개요

  • 인덱서를 사용하면 배열과 비슷한 방식으로 개체를 인덱싱할 수 있습니다.

  • get 접근자는 값을 반환합니다. set 접근자는 값을 할당합니다.

  • this 키워드는 인덱서를 정의하는 데 사용됩니다.

  • value 키워드는 set 인덱서로 할당되는 값을 정의하는 데 사용됩니다.

  • 인덱서를 반드시 정수 값으로 인덱싱할 필요는 없습니다. 특정 조회 메커니즘을 정의하는 방법은 사용자가 선택할 수 있습니다.

  • 인덱서는 오버로드할 수 없습니다.

  • 2차원 배열에 액세스하는 경우와 같이 인덱서에는 여러 개의 정식 매개 변수가 있을 수 있습니다.

관련 단원

C# 언어 사양

자세한 내용은 C# 언어 사양을 참조하십시오. 이 언어 사양은 C# 구문 및 사용법에 대한 신뢰할 수 있는 소스입니다.

참고 항목

참조

속성(C# 프로그래밍 가이드)

개념

C# 프로그래밍 가이드