How to: Explicitly Implement Interface Members 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

How to: Explicitly Implement Interface Members



This example declares an interface, IDimensions, and a class, Box, which explicitly implements the interface members getLength and getWidth. The members are accessed through the interface instance dimensions.

Example

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()); } }
Length: 30 Width: 20

Явная реализация членов интерфейса

В этом примере выполняется объявление интерфейса, IDimensions, и класса, Box, который явно реализует члены интерфейса getLength и getWidth. Доступ к этим членам осуществляется через экземпляр интерфейса dimensions.

Пример

ß-----


Robust Programming

· Notice that the following lines, in the Main method, are commented out because they would produce compilation errors. An interface member that is explicitly implemented cannot be accessed from a class instance:

//System.Console.WriteLine("Length: {0}", box1.getlength()); //System.Console.WriteLine("Width: {0}", box1.getwidth());

· Notice also that the following lines, in the Main method, successfully print out the dimensions of the box because the methods are being called from an instance of the interface:

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

 


Надежное программирование

· Обратите внимание, что следующие строки в методе 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());

 


How to: Explicitly Implement Interface Members with Inheritance

Explicit interface implementation also allows the programmer to implement two interfaces that have the same member names and give each interface member a separate implementation. This example displays the dimensions of a box in both metric and English units. The Boxclass implements two interfaces IEnglishDimensions and IMetricDimensions, which represent the different measurement systems. Both interfaces have identical member names, Length and Width.

Example

// 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 length, float width)

{

lengthInches = length;

widthInches = width;

}

 



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 104; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 18.118.226.105 (0.006 с.)