Книга: C# 2008 Programmer

Implementing Callbacks Using Delegates

Implementing Callbacks Using Delegates

One of the useful things you can do with delegates is to implement callbacks. Callbacks are methods that you pass into a function that will be called when the function finishes execution. For example, you have a function that performs a series of mathematical operations. When you call the function, you also pass it a callback method so that when the function is done with its calculation, the callback method is called to notify you of the calculation result.

Following is an example of how to implement callbacks using delegates:

class Program {
 delegate void callbackDelegate(string Message);
 static void Main(string[] args) {
  callbackDelegate result = ResultCallback;
  AddTwoNumbers(5, 3, result);
  Console.ReadLine();
 }
 static private void AddTwoNumbers(
  int num1, int num2, callbackDelegate callback) {
  int result = num1 + num2;
  callback("The result is: " + result.ToString());
 }
 static private void ResultCallback(string Message) {
  Console.WriteLine(Message);
 }
}

First, you declare two methods:

AddTwoNumbers() — Takes in two integer arguments and a delegate of type callbackDelegate

ResultCallback() — Takes in a string argument and displays the string in the console window

Then you declare a delegate type:

delegate void callbackDelegate(string Message);

Before you call the AddTwoNumbers() function, you create a delegate of type callbackDelegate and assign it to point to the ResultCallback() method. The AddTwoNumbers() function is then called with two integer arguments and the result callback delegate:

callbackDelegate result = ResultCallback;
AddTwoNumbers(5, 3, result);

In the AddTwoNumbers() function, when the calculation is done, you invoke the callback delegate and pass to it a string:

static private void AddTwoNumbers(
 int num1, int num2, callbackDelegate callback) {
 int result = num1 + num2;
 callback("The result is: " + result.ToString());
}

The callback delegate calls the ResultCallback() function, which prints the result to the console. The output is:

The result is: 8

Оглавление книги


Генерация: 1.243. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз