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

CHAPTER 19 GENERICS

Generic Delegates

Generic delegates are very much like nongeneric delegates, except that the type parameters determine the characteristics of what methods will be accepted.

To declare a generic delegate, place the type parameter list in angle brackets after the delegate name and before the delegate parameter list.

Type parameters

delegate R MyDelegate<T, R>( T value );

 

 

Return type

Delegate formal parameter

Notice that there are two parameter lists: the delegate formal parameter list and the type parameter list.

The scope of the type parameters includes the following:

The return type

The formal parameter list

The constraint clauses

488

CHAPTER 19 GENERICS

The following code shows an example of a generic delegate. In Main, generic delegate MyDelegate is instantiated with an argument of type string and initialized with method PrintString.

delegate void MyDelegate<T>(T value);

//

Generic delegate

 

 

 

class Simple

 

 

{

 

 

static public void PrintString(string s)

//

Method matches delegate

{

 

 

Console.WriteLine(s);

 

 

}

 

 

 

 

 

static public void PrintUpperString(string s)

//

Method matches delegate

{

 

 

Console.WriteLine("{0}", s.ToUpper());

 

 

}

 

 

}

 

 

class Program

 

 

{

 

 

static void Main( )

 

 

{

 

 

var myDel =

//

Create inst of delegate

new MyDelegate<string>(Simple.PrintString);

 

myDel += Simple.PrintUpperString;

//

Add a method.

myDel("Hi There.");

//

Call delegate

}

}

This code produces the following output:

Hi There.

HI THERE.

489

CHAPTER 19 GENERICS

Another Generic Delegate Example

Since the LINQ feature of C# 3.0 uses generic delegates extensively, it’s worth showing another example before we get there. I’ll cover LINQ itself, and more about its generic delegates, in Chapter 21.

The following code declares a generic delegate named Func, which takes methods with two parameters and that return a value. The method return type is represented as TR, and the method parameter types are represented as T1 and T2.

Delegate parameter type

↓ ↓ ↓ ↓

public delegate TR Func<T1, T2, TR>(T1 p1, T2 p2); // Generic delegate

 

class Simple

Delegate return type

{

 

 

static public string PrintString(int p1, int p2) // Method matches delegate

{

int total = p1 + p2; return total.ToString();

}

}

 

class Program

 

{

 

static void Main()

 

{

 

var myDel =

// Create inst of delegate

new Func<int, int, string>(Simple.PrintString);

Console.WriteLine("Total: {0}", myDel(15, 13)); // Call delegate

}

}

This code produces the following output:

Total: 28

490

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