logo search
CSharp_Prog_Guide

Объединение делегатов (многоадресные делегаты)

В этом примере демонстрируется способ компоновки многоадресных делегатов. Полезное свойство объектов делегат заключается в том, что они могут быть присвоены одному экземпляру делегата (при этом он станет многоадресным) с помощью оператора +. Составной делегат вызывает два делегата, из которых он составлен. Допускается составление делегатов только одного типа.

Оператор - служит для удаления делегата-компонента из составного делегата.

Пример

----

How to: Declare, Instantiate, and Use a Delegate

In C# 1.0 and later, delegates can be declared as shown here:

public delegate void Del<T>(T item);

public void Notify(int i) { }

Del<int> d1 = new Del<int>(Notify);

In C# 2.0 and later, it is also possible to use an anonymous method to declare and initialize a delegate by using this simplified syntax:

Del<int> d2 = Notify;

In C# 3.0 and later, delegates can also be declared and instantiated by using a lambda expression.

The following example illustrates declaring, instantiating, and using a delegate. The BookDB class encapsulates a bookstore database that maintains a database of books. It exposes a method, ProcessPaperbackBooks, which finds all paperback books in the database and calls a delegate for each one. The delegate type that is used is named ProcessBookDelegate. The Test class uses this class to print the titles and average price of the paperback books.

The use of delegates promotes good separation of functionality between the bookstore database and the client code. The client code has no knowledge of how the books are stored or how the bookstore code finds paperback books. The bookstore code has no knowledge of what processing is performed on the paperback books after it finds them.