Книга: 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
- Delegates
- Delegates Chaining (Multicast Delegates)
- Caveats using NAT
- Using Double Quotes to Resolve Variables in Strings with Embedded Spaces
- Data Binding Using the GridView Control
- Using the kill Command to Control Processes
- Installing Using a Network
- Using X
- Using a Display Manager
- Starting X from the Console by Using startx
- Using Fedora's switchdesk Client
- Using Environment Variables