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

CHAPTER 17 INTERFACES

What Is an Interface?

An interface is a reference type that specifies a set of function members but does not implement them. Other types—classes or structs—can implement interfaces.

To get a feeling for interfaces, I’ll start by showing one that is already defined. The BCL declares an interface called IComparable, the declaration of which is shown in the following code. Notice that the interface body contains the declaration of a single method, CompareTo, which takes a single parameter of type object. Although the method has a name, parameters, and a return type, there is no implementation. Instead, the implementation is replaced by a semicolon.

Keyword

Interface name

public

interface IComparable

 

{

 

 

int

CompareTo( object obj

);

}

 

Semicolon in place of method implementation

Figure 17-1 illustrates interface IComparable. The CompareTo method is shown in gray to illustrate that it doesn’t contain an implementation.

Figure 17-1. Representation of interface IComparable

Although the interface declaration doesn't provide an implementation for method CompareTo, the

.NET documentation of interface IComparable describes what the method should do, in case you create a class or struct that implements the interface. It says that when method CompareTo is called, it should return one of the following values:

A negative value, if the current object is less than the parameter object

A positive value, if the current object is greater than the parameter object

Zero, if the two objects are considered equal in the comparison

410

CHAPTER 17 INTERFACES

Example Using the IComparable Interface

To understand what this means and why it’s useful, let’s start by taking a look at the following code, which takes an unsorted array of integers and sorts them in ascending order.

The first line creates an array of five integers that are in no particular order.

The second line uses the Array class’s static Sort method to sort the elements.

The foreach loop prints them out, showing that the integers are now in ascending order.

var myInt = new [] { 20,

4, 16, 9, 2 };

// Create an array

of ints.

Array.Sort(myInt);

 

//

Sort elements by magnitude.

foreach (var i in myInt)

 

//

Print them out.

 

Console.Write("{0} ",

i);

 

 

 

This code produces the following output:

2 4 9 16 20

The Array class’s Sort method works great on an array of ints, but what would happen if you were to try to use it on one of your own classes, as shown here?

class MyClass

// Declare a

simple class.

{

 

 

 

public int TheValue;

 

 

 

}

 

 

 

...

 

 

 

MyClass[] mc = new MyClass[5];

// Create

an array of five elements.

...

// Create

and

initialize the elements.

Array.Sort(mc);

// Try to

use

Sort--raises exception

When you try to run this code, it raises an exception instead of sorting the elements. The reason Sort doesn’t work with the array of MyClass objects is that it doesn’t know how to compare user-defined objects and how to rank their order.

The algorithm used by Sort depends on the fact that it can use the element’s CompareTo method to determine the order of two elements. The int type implements IComparable, but MyClass does not, so when Sort tries to call the nonexistent CompareTo method of MyClass, it raises an exception.

411

CHAPTER 17 INTERFACES

You can make the Sort method work with objects of type MyClass by making the class implement IComparable. To implement an interface, a class or struct must do two things:

It must list the interface name in its base class list.

It must provide an implementation for each of the interface’s members.

For example, the following code updates MyClass to implement interface IComparable. Notice the following about the code:

The name of the interface is listed in the base class list of the class declaration.

The class implements a method called CompareTo, whose parameter type and return type match those of the interface member.

Method CompareTo is implemented to satisfy the definition given in the interface’s documentation. That is, it returns a negative 1, positive 1, or 0, depending on its value compared to the object passed into the method.

Interface name in base class list

class MyClass : IComparable

{

public int TheValue;

public int

CompareTo(object obj)

// Implementation of interface method

{

 

 

MyClass

mc = (MyClass)obj;

 

if (this.TheValue < mc.TheValue) return -1; if (this.TheValue > mc.TheValue) return 1; return 0;

}

}

Figure 17-2 illustrates the updated class. The arrow from the grayed interface method to the class method indicates that the interface method doesn’t contain code but is implemented by the class-level method.

Figure 17-2. Implementing IComparable in MyClass

412

CHAPTER 17 INTERFACES

Now that MyClass implements IComparable, Sort will work on it just fine. It would not, by the way, have been sufficient to just declare the CompareTo method—it must be part of implementing the interface, which means placing the interface name in the base class list.

The following shows the complete updated code, which can now use the Sort method to sort an array of MyClass objects. Main creates and initializes an array of MyClass objects and then prints them out. It then calls Sort and prints them out again to show that they’ve been sorted.

class MyClass

: IComparable

// Class implements interface.

{

 

 

public int

TheValue;

 

public int

CompareTo(object obj)

// Implement the method.

{

 

 

MyClass

mc = (MyClass)obj;

 

if (this.TheValue < mc.TheValue) return -1; if (this.TheValue > mc.TheValue) return 1; return 0;

}

}

class Program

{

static void PrintOut(string s, MyClass[] mc)

{

Console.Write(s); foreach (var m in mc)

Console.Write("{0} ", m.TheValue); Console.WriteLine("");

}

static void Main()

{

var myInt = new [] { 20, 4, 16, 9, 2 };

MyClass[] mcArr = new MyClass[5]; for (int i = 0; i < 5; i++)

{

mcArr[i] = new MyClass(); mcArr[i].TheValue = myInt[i];

//Create array of MyClass objs.

//Initialize the array.

}

PrintOut("Initial Order: ", mcArr); // Print the initial array. Array.Sort(mcArr); // Sort the array. PrintOut("Sorted Order: ", mcArr); // Print the sorted array.

}

}

This code produces the following output:

Initial Order: 20 4 16 9 2

Sorted Order: 2 4 9 16 20

413

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