다음을 통해 공유


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

명시적 인터페이스 구현을 사용하면 프로그래머가 멤버 이름이 같은 두 인터페이스를 구현하고 각 인터페이스 멤버에 별도의 구현을 제공할 수 있습니다. 다음은 상자의 크기를 메트릭 단위와 영어 단위로 표시하는 예제입니다. Box 클래스 는 서로 다른 측정 시스템을 나타내는 두 개의 인터페이스 IEnglishDimensions 및 IMetricDimensions를 구현합니다. 두 인터페이스 모두 길이와 너비의 멤버 이름이 동일합니다.

예시

// Declare the English units interface:
interface IEnglishDimensions
{
    float Length();
    float Width();
}

// Declare the metric units interface:
interface IMetricDimensions
{
    float Length();
    float Width();
}

// Declare the Box class that implements the two interfaces:
// IEnglishDimensions and IMetricDimensions:
class Box : IEnglishDimensions, IMetricDimensions
{
    float _lengthInches;
    float _widthInches;

    public Box(float lengthInches, float widthInches)
    {
        _lengthInches = lengthInches;
        _widthInches = widthInches;
    }

    // Explicitly implement the members of IEnglishDimensions:
    float IEnglishDimensions.Length() => _lengthInches;

    float IEnglishDimensions.Width() => _widthInches;

    // Explicitly implement the members of IMetricDimensions:
    float IMetricDimensions.Length() => _lengthInches * 2.54f;

    float IMetricDimensions.Width() => _widthInches * 2.54f;

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

        // Declare an instance of the English units interface:
        IEnglishDimensions eDimensions = box1;

        // Declare an instance of the metric units interface:
        IMetricDimensions mDimensions = box1;

        // Print dimensions in English units:
        Console.WriteLine($"Length(in): {eDimensions.Length()}");
        Console.WriteLine($"Width (in): {eDimensions.Width()}");

        // Print dimensions in metric units:
        Console.WriteLine($"Length(cm): {mDimensions.Length()}");
        Console.WriteLine($"Width (cm): {mDimensions.Width()}");
    }
}
/* Output:
    Length(in): 30
    Width (in): 20
    Length(cm): 76.2
    Width (cm): 50.8
*/

강력한 프로그래밍

영어 단위로 기본 측정을 수행하려면 일반적으로 Length 및 Width 메서드를 구현하고 IMetricDimensions 인터페이스에서 Length 및 Width 메서드를 명시적으로 구현합니다.

// Normal implementation:
public float Length() => _lengthInches;
public float Width() => _widthInches;

// Explicit implementation:
float IMetricDimensions.Length() => _lengthInches * 2.54f;
float IMetricDimensions.Width() => _widthInches * 2.54f;

이 경우 클래스 인스턴스에서 영어 단위에 액세스하고 인터페이스 인스턴스에서 메트릭 단위에 액세스할 수 있습니다.

public static void Test()
{
    Box box1 = new(30.0f, 20.0f);
    IMetricDimensions mDimensions = box1;

    Console.WriteLine($"Length(in): {box1.Length()}");
    Console.WriteLine($"Width (in): {box1.Width()}");
    Console.WriteLine($"Length(cm): {mDimensions.Length()}");
    Console.WriteLine($"Width (cm): {mDimensions.Width()}");
}

참고하십시오