Поделиться через


Как явно реализовать члены интерфейса (Руководство по программированию на C#)

В этом примере объявляется интерфейс и IDimensionsкласс, Boxкоторый явным образом реализует члены GetLength интерфейса и GetWidth. К членам обращаются через экземпляр интерфейса 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()}");
    

См. также