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

CHAPTER 19 GENERICS

Generic Methods

Unlike the other generics, a method is not a type but a member. You can declare generic methods in both generic and nongeneric classes, and in structs and interfaces, as shown in Figure 19-10.

Figure 19-10. Generic methods can be declared in generic and nongeneric types.

481

CHAPTER 19 GENERICS

Declaring a Generic Method

Generic methods have a type parameter list and optional constraints.

Generic methods have two parameter lists:

The method parameter list, enclosed in parentheses

The type parameter list, enclosed in angle brackets

To declare a generic method, do the following:

Place the type parameter list immediately after the method name and before the method parameter list.

Place any constraint clauses after the method parameter list.

Type parameter list

Constraint clauses

 

 

public void PrintData<S, T> ( S p, T t ) where S: Person

{

...

Method parameter list

}

 

Note Remember that the type parameter list goes after the method name and before the method parameter list.

482

CHAPTER 19 GENERICS

Invoking a Generic Method

To invoke a generic method, supply type arguments with the method invocation, as shown here:

Type arguments

MyMethod<short, int>();

MyMethod<int, long >();

Figure 19-11 shows the declaration of a generic method called DoStuff, which takes two type parameters. Below it are two places where the method is called, each with a different set of type parameters. Each of these constructed instances produces a different version of the method, as shown on the right of the figure.

Figure 19-11. A generic method with two instantiations

483

CHAPTER 19 GENERICS

Inferring Types

If you are passing parameters into a method, the compiler can sometimes infer from the types of the method parameters the types that should be used as the type parameters of the generic method. This can make the method calls simpler and easier to read.

For example, the following code declares MyMethod, which takes a method parameter of the same type as the type parameter.

public void MyMethod <T> (T myVal) { ... }

Both are of type T

If you invoke MyMethod with a variable of type int, as shown in the following code, the information in the type parameter of the method invocation is redundant, since the compiler can see from the method parameter that it’s an int.

int myInt = 5;

MyMethod <int> (myInt);

↑ ↑

Both are ints

Since the compiler can infer the type parameter from the method parameter, you can omit the type parameter and its angle brackets from the invocation, as shown here:

MyMethod(myInt);

484

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