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

CHAPTER 19 GENERICS

Example of a Generic Method

The following code declares a generic method called ReverseAndPrint in a nongeneric class called Simple. The method takes as its parameter an array of any type. Main declares three different array types. It then calls the method twice with each array. The first time it calls the method with a particular array, it explicitly uses the type parameter. The second time, the type is inferred.

class Simple

 

 

// Non-generic class

{

 

 

 

static public void ReverseAndPrint<T>(T[] arr)

// Generic method

{

 

 

 

Array.Reverse(arr);

 

 

foreach (T item in arr)

 

// Use type argument T.

Console.Write("{0}, ", item.ToString());

 

Console.WriteLine("");

 

 

}

 

 

 

}

 

 

 

class Program

 

 

 

{

 

 

 

static void Main()

 

 

 

{

 

 

 

// Create arrays of various types.

 

var intArray

= new int[]

{ 3, 5, 7, 9, 11 };

var stringArray = new string[] { "first", "second", "third" };

var doubleArray = new double[] { 3.567, 7.891, 2.345 };

Simple.ReverseAndPrint<int>(intArray);

// Invoke method

Simple.ReverseAndPrint(intArray);

// Infer type and invoke

Simple.ReverseAndPrint<string>(stringArray);

// Invoke method

Simple.ReverseAndPrint(stringArray);

// Infer type and invoke

Simple.ReverseAndPrint<double>(doubleArray);

// Invoke method

Simple.ReverseAndPrint(doubleArray);

// Infer type and invoke

}

 

 

 

}

 

 

 

This code produces the following output:

11, 9, 7, 5, 3, 3, 5, 7, 9, 11,

third, second, first, first, second, third, 2.345, 7.891, 3.567, 3.567, 7.891, 2.345,

485

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