다음을 통해 공유


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

이 예제에서는 인터페이스IDimensions 멤버 GetLengthGetWidth를 명시적으로 구현하는 인터페이스 및 클래스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(30.0f, 20.0f);

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

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

        // Print out the dimensions of the box by calling the methods
        // from an instance of the interface:
        Console.WriteLine($"Length: {dimensions.GetLength()}");
        Console.WriteLine($"Width: {dimensions.GetWidth()}");
    }
}
/* Output:
    Length: 30
    Width: 20
*/

강력한 프로그래밍

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

    //Console.WriteLine($"Length: {box1.GetLength()}");
    //Console.WriteLine($"Width: {box1.GetWidth()}");
    
  • 또한 Main 메서드에서 인터페이스 인스턴스에서 메서드를 호출하기 때문에 다음 줄이 상자의 차원을 성공적으로 출력합니다.

    Console.WriteLine($"Length: {dimensions.GetLength()}");
    Console.WriteLine($"Width: {dimensions.GetWidth()}");
    

참고하십시오