basically enables you to reference a function without directly invoking the function. Delegates are often used to implement techniques called callbacks, which means that after a function has finished execution, a call is made to a specific function to inform it that the execution has completed. In addition, delegates are also used in event handling. Despite the usefulness of delegates, it is a topic that not all .NET programmers are familiar with. An event, on the other hand, is used by classes to notify clients when something of interest has happened. For example, a Button control has the Click event, which allows your program to be notified when someone clicks the button.

This chapter explores the following:

□ What is a delegate?

□ Using delegates

□ Implementing callbacks using a delegate

□ What are events?

□ How to handle and implement events in your program

Delegates

In C#, a delegate is a reference type that contains a reference to a method. Think of a delegate as a pointer to a function. Instead of calling a function directly, you use a delegate to point to it and then invoke the method by calling the delegate. The following sections explain how to use a delegate and how it can help improve the responsiveness of your application. 

Creating a Delegate

To understand the use of delegates, begin by looking at the conventional way of invoking a function. Consider the following program:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Delegates {

 class Program {

  static void Main(string[] args) {

   int num1 = 5;

   int num2 = 3;

   Console.WriteLine(Add(num1, num2).ToString());

   Console.WriteLine(Subtract(num1, num2).ToString());

   Console.ReadLine();

  }

  static int Add(int num1, int num2) {

   return (num1 + num2);

  }

  static int Subtract(int num1, int num2) {

   return (num1 - num2);

  }

 }

}

The program contains three methods: Main(), Add(), and Subtract(). Notice that the Add() and Subtract() methods have the same signature. In the Main() method, you invoke the Add() and Subtract() methods by calling them directly, like this:

Console.WriteLine(Add(num1, num2).ToString());

Console.WriteLine(Subtract(num1, num2).ToString());

Now create a delegate type with the same signature as the Add() method:

namespace Delegates {

 class Program {

  delegate int MethodDelegate(int num1, int num2);

  static void Main(string[] args) {

   ...

You define a delegate type by using the delegate keyword, and its declaration is similar to that of a function, except that a delegate has no function body.

To make a delegate object point to a function, you create an object of that delegate type (MethodDelegate, in this case) and instantiate it with the method you want to point to, like this:

static void Main(string[] args) {

 int num1 = 5;

 int num2 = 3;

 MethodDelegate method = new MethodDelegate(Add);

Alternatively, you can also assign the function name to it directly, like this:

MethodDelegate method = Add;

This statement declares method to be a delegate that points to the Add() method. Hence instead of calling the Add() method directly, you can now call it using the method delegate:

//---Console.WriteLine(Add(num1, num2).ToString());---

Console.WriteLine(method(num1, num2).ToString());

The beauty of delegates is that you can make the delegate call whatever function it refers to, without knowing exactly which function it is calling until runtime. Any function can be pointed by the delegate, as long as the function's signature matches the delegate's.

For example, the following statements check the value of the Operation variable before deciding which method the method delegate to point to:

char Operation = 'A';

MethodDelegate method = null;

switch (Operation) {

case 'A':

 method = new MethodDelegate(Add);

 break;

case 'S':

 method = new MethodDelegate(Subtract);

 break;

}

if (method != null)

 Console.WriteLine(method(num1, num2).ToString());

You can also pass a delegate to a method as a parameter, as the following example shows:

using System;

using System.Collections.Generic;

Вы читаете C# 2008 Programmer's Reference
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату