다음을 통해 공유


인터페이스의 인덱서(C# 프로그래밍 가이드)

interface(C# 참조)에서 인덱서를 선언할 수 있습니다. 인터페이스 인덱서의 접근자와 클래스 인덱서의 접근자는 다음과 같은 차이점이 있습니다.

  • 인터페이스 접근자는 한정자를 사용하지 않습니다.

  • 인터페이스 접근자에는 본문이 없습니다.

따라서 접근자의 목적은 인덱서가 읽기/쓰기, 읽기 전용 또는 쓰기 전용인지 여부를 나타내는 것입니다.

다음은 인터페이스 인덱서 접근자의 예제입니다.

public interface ISomeInterface
{
    //... 

    // Indexer declaration: 
    string this[int index]
    {
        get;
        set;
    }
}

인덱서의 시그니처는 같은 인터페이스에 선언된 다른 모든 인덱서의 시그니처와 달라야 합니다.

예제

다음 예제는 인터페이스 인덱서의 구현 방법을 보여 줍니다.

    // Indexer on an interface: 
    public interface ISomeInterface
    {
        // Indexer declaration: 
        int this[int index]
        {
            get;
            set;
        }
    }

    // Implementing the interface. 
    class IndexerClass : ISomeInterface
    {
        private int[] arr = new int[100];
        public int this[int index]   // indexer declaration
        {
            get
            {
                // The arr object will throw IndexOutOfRange exception. 
                return arr[index];
            }
            set
            {
                arr[index] = value;
            }
        }
    }

    class MainClass
    {
        static void Main()
        {
            IndexerClass test = new IndexerClass();
            System.Random rand = new System.Random();
            // Call the indexer to initialize its elements. 
            for (int i = 0; i < 10; i++)
            {
                test[i] = rand.Next();
            }
            for (int i = 0; i < 10; i++)
            {
                System.Console.WriteLine("Element #{0} = {1}", i, test[i]);
            }

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
    /* Sample output:
        Element #0 = 360877544
        Element #1 = 327058047
        Element #2 = 1913480832
        Element #3 = 1519039937
        Element #4 = 601472233
        Element #5 = 323352310
        Element #6 = 1422639981
        Element #7 = 1797892494
        Element #8 = 875761049
        Element #9 = 393083859
     */

위 예제에서 인터페이스 멤버의 정규화된 이름을 사용하여 명시적 인터페이스 멤버를 구현할 수 있습니다. 예를 들면 다음과 같습니다.

public string ISomeInterface.this 
{ 
} 

그러나 정규화된 이름은 클래스에서 인덱서 시그니처가 같은 두 개 이상의 인터페이스를 구현하는 경우에 모호성을 피하고자 할 때 필요합니다. 예를 들어, Employee 클래스가 ICitizen 및 IEmployee라는 두 개의 인터페이스를 구현하고 두 인터페이스에 동일한 인덱서 시그니처가 있는 경우 해당 인터페이스 멤버를 명시적으로 구현해야 합니다. 예를 들면 다음과 같습니다.

public string IEmployee.this 
{ 
} 

위의 선언은 IEmployee 인터페이스에서 인덱서를 구현합니다.

public string ICitizen.this 
{ 
} 

그러나 위의 선언은 ICitizen 인터페이스에서 인덱서를 구현합니다.

참고 항목

참조

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

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

인터페이스(C# 프로그래밍 가이드)

개념

C# 프로그래밍 가이드