Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
26
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

246 Part II Understanding the C# Language

a default implementation in the abstract class and you want to ensure that an inheriting class provides its own implementation of that method.

abstract class GrazingMammal : Mammal, IGrazable

{

abstract void DigestGrass();

...

}

Sealed Classes

Using inheritance is not always easy and requires forethought. If you create an interface or an abstract class, you are knowingly writing something that will be inherited from in the future. The trouble is that predicting the future is a difficult business. With practice and experience, you can develop the skills to craft a flexible, easy-to-use hierarchy of interfaces, abstract classes, and classes, but it takes effort and you also need a solid understanding of the problem you are modeling. To put it another way, unless you consciously design a class with the

intention of using it as a base class, it’s extremely unlikely that it will function very well as a base class. C# allows you to use the sealed keyword to prevent a class from being used as a

base class if you decide that it should not be. For example:

sealed class Horse : GrazingMammal, ILandBound

{

...

}

If any class attempts to use Horse as a base class, a compile-time error will be generated. Note that a sealed class cannot declare any virtual methods and that an abstract class cannot be sealed.

Note A structure is implicitly sealed. You can never derive from a structure.

Sealed Methods

You can also use the sealed keyword to declare that an individual method in an unsealed

class is sealed. This means that a derived class cannot then override the sealed method. You can seal only an override method. (You declare the method as sealed override.) You can think of the interface, virtual, override, and sealed keywords as follows:

An interface introduces the name of a method.

A virtual method is the first implementation of a method.

An override method is another implementation of a method.

A sealed method is the last implementation of a method.

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