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

CHAPTER 19 GENERICS

Generics in C#

With C# 2.0, Microsoft introduced the generics features, which offer more elegant ways of using a set of code with more than one type. Generics allow you to declare type-parameterized code, which you can instantiate with different types. This means you can write the code with “placeholders for types” and then supply the actual types when you create an instance of the class.

By this point in the text, you should be very familiar with the concept that a type is not an object but a template for an object. In the same way, a generic type is not a type but a template for a type. Figure 19-1 illustrates this point.

Figure 19-1. Generic types are templates for types.

C# provides five kinds of generics: classes, structs, interfaces, delegates, and methods. Notice that the first four are types, and methods are members.

Figure 19-2 shows how generic types fit in with the other types covered.

Figure 19-2. Generics and user-defined types

468

CHAPTER 19 GENERICS

Continuing with the Stack Example

In the stack example, with classes MyIntStack and MyFloatStack, the bodies of the declarations of the classes are identical except at the positions dealing with the type of the value held by the stack.

In MyIntStack, these positions are occupied by type int.

In MyFloatStack, they are occupied by float.

You can create a generic class from MyIntStack by doing the following:

Take the MyIntStack class declaration, and instead of substituting float for int, substitute the type placeholder T.

Change the class name to MyStack.

Place the string <T> after the class name.

The result is the following generic class declaration. The string consisting of the angle brackets with the T means that T is a placeholder for a type. (It doesn’t have to be the letter T—it can be any identifier.) Everywhere throughout the body of the class declaration where T is located, an actual type will need to be substituted by the compiler.

class MyStack <T>

{

int StackPointer = 0;

T [] StackArray;

public void Push(T x ) {...}

public T Pop() {...}

...

}

469

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