Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 17 INTERFACES

Implementing an Interface

Only classes or structs can implement an interface. As shown in the Sort example, to implement an interface, a class or struct must

Include the name of the interface in its base class list

Supply implementations for each of the interface’s members

For example, the following code shows a new declaration for class MyClass, which implements interface IMyInterface1, declared in the previous section. Notice that the interface name is listed in the base class list after the colon and that the class provides the actual implementation code for the interface members.

 

Colon Interface name

 

class MyClass: IMyInterface1

{

 

 

int

DoStuff

( int nVar1, long lVar2 )

{ ... }

 

// Implementation code

double DoOtherStuff( string s, long x )

{ ... }

 

// Implementation code

}

 

 

Some important things to know about implementing interfaces are the following:

If a class implements an interface, it must implement all the members of that interface.

If a class is derived from a base class and also implements interfaces, the name of the base class must be listed in the base class list before any interfaces, as shown here:

Base class must be first

Interface names

 

class Derived : MyBaseClass, IIfc1, IEnumerable, IComparable

{

...

}

416

CHAPTER 17 INTERFACES

Example with a Simple Interface

The following code declares an interface named IIfc1, which contains a single method named PrintOut. Class MyClass implements interface IIfc1 by listing it in its base class list and supplying a method named PrintOut that matches the signature and return type of the interface member. Main creates an object of the class and calls the method from the object.

interface IIfc1

Semicolon in place of body

// Declare interface

{

 

void PrintOut(string s);

 

}

 

 

Implement interface

 

 

 

class MyClass : IIfc1

// Declare class

{

 

 

public void PrintOut(string s)

// Implementation

{

 

 

Console.WriteLine("Calling through:

{0}", s);

}

 

 

}

 

 

class Program

 

 

{

 

 

static void Main()

 

{

 

 

MyClass mc = new MyClass();

// Create instance

mc.PrintOut("object");

// Call method

}

 

 

}

 

 

This code produces the following output:

Calling through: object

417

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]