다음을 통해 공유


방법: 인터페이스 멤버를 명시적으로 구현(C# 프로그래밍 가이드)

다음 예제에서는 IDimensions 인터페이스를 선언한 다음 인터페이스 멤버인 getLength와 getWidth를 명시적으로 구현하는 Box 클래스를 선언합니다. 멤버는 인터페이스 인스턴스 dimensions을 통해 액세스할 수 있습니다.

예제

interface IDimensions
{
    float getLength();
    float getWidth();
}

class Box : IDimensions
{
    float lengthInches;
    float widthInches;

    Box(float length, float width)
    {
        lengthInches = length;
        widthInches = width;
    }
    // Explicit interface member implementation:  
    float IDimensions.getLength()
    {
        return lengthInches;
    }
    // Explicit interface member implementation: 
    float IDimensions.getWidth()
    {
        return widthInches;
    }

    static void Main()
    {
        // Declare a class instance box1:
        Box box1 = new Box(30.0f, 20.0f);

        // Declare an interface instance dimensions:
        IDimensions dimensions = (IDimensions)box1;

        // The following commented lines would produce compilation  
        // errors because they try to access an explicitly implemented 
        // interface member from a class instance:                    
        //System.Console.WriteLine("Length: {0}", box1.getLength());
        //System.Console.WriteLine("Width: {0}", box1.getWidth());

        // Print out the dimensions of the box by calling the methods  
        // from an instance of the interface:
        System.Console.WriteLine("Length: {0}", dimensions.getLength());
        System.Console.WriteLine("Width: {0}", dimensions.getWidth());
    }
}
/* Output:
    Length: 30
    Width: 20
*/

강력한 프로그래밍

  • Main 메서드에서 다음 줄은 컴파일 오류를 발생시키므로 주석 처리합니다. 명시적으로 구현된 인터페이스 멤버는 클래스 인스턴스에서 액세스할 수 없습니다.

    //System.Console.WriteLine("Length: {0}", box1.getLength());
    //System.Console.WriteLine("Width: {0}", box1.getWidth());
    
  • 또한, 메서드는 인터페이스의 인스턴스에서 호출되므로 Main 메서드에서 다음 줄은 상자의 크기를 성공적으로 출력합니다.

    System.Console.WriteLine("Length: {0}", dimensions.getLength());
    System.Console.WriteLine("Width: {0}", dimensions.getWidth());
    

참고 항목

작업

방법: 두 인터페이스의 멤버를 명시적으로 구현(C# 프로그래밍 가이드)

참조

클래스 및 구조체(C# 프로그래밍 가이드)

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

개념

C# 프로그래밍 가이드