Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лаба №1 / books / csharp_ebook.pdf
Скачиваний:
63
Добавлен:
03.03.2016
Размер:
3.69 Mб
Скачать

Programmers Heaven: C# School

9. Delegates & Events

Lesson Plan

Today we will explore the concept of delegates and events. We will start out by looking at the idea behind delegates and will see how delegates are used in C#. Later, we will explore multicast delegates and their significance. Finally, we will learn about events and event handling mechanism in C# through delegates.

Delegates Basics

Delegates are references to methods. So far we have used references to objects, e.g. Stack st = new Stack(); Here st is a reference to an object of the Stack class type. Hence, each reference has two properties: 1. The type of object (class) the reference can point to. 2. The actual object referenced (or pointed to) by the reference.

Delegates are similar to object references, but are used to reference methods instead of objects. The type of a delegate is the type or signature of the method rather than the class. Hence a delegate has three properties:

1.The type or signature of the method that the delegate can point to

2.The delegate reference which can be used to reference a method

3.The actual method referenced by the delegate

Author's Note: The concept of delegates is similar to the function pointers used in C++.

An Object

Points to

An object of

Reference

 

 

particular type

 

 

 

 

A Delegate

Points to

A method of

 

 

particular type

 

 

 

 

 

 

 

The type or signature of the method the delegate can point to

Before using a delegate, we need to specify the type or signature of the method the delegate can reference. The signature of a method includes its return type and the type of parameters which it requires to be passed.

171

Programmers Heaven: C# School

For example:

int someMethod(string [] args)

Is the common signature of the Main() method of a C# programs defined as:

int Main(string [] args)

{

...

}

And for the following Add() method:

int Add(int a, int b)

{

return a+b;

}

The signature will be:

int aMethod(int p, int q)

Which is also the signature of following Subtract() method:

int Subtract(int c, int d)

{

return c-d;

}

It should be noticed from the above examples that the name of a method is not the part of its signature; the signature only involves its return type and parameters.

In case of delegates, we define the type of a delegate using the delegate keyword, e.g.

delegate int MyDelegate(int p, int q);

Here we have defined a delegate type with the name 'MyDelegate'. The reference of this delegate type can be used to point to any method which takes two integers as parameters and returns an integer value.

172

Programmers Heaven: C# School

The delegate reference, that can be used to reference a method

Once we have defined a delegate type, we can set it to reference actual methods with matching signatures. A delegate reference can be declared just like an object reference. For example, a reference of type MyDelegate (defined above) can be declared as:

MyDelegate arithMethod;

The delegate reference arithMethod can now reference any method whose signature is identical to the signature of MyDelegate.

3.The actual method referenced by the delegate

The delegate reference can be made to reference any method with a matching signature by passing its name as the parameter of delegate:

arithMethod = new MyDelegate(Add);

Here, the arithMethod delegate reference is made to point to the Add() method by passing its name as a parameter to the delegate type (MyDelegate). The last two steps can be merged together in a single statement, like this:-

MyDelegate arithMethod = new MyDelegate(Add);

Calling the actual method through its delegate

Once the delegate reference 'arithMethod' has been made to point to the Add() method, it can be used to call the actual method like this:-

int r = arithMethod(3, 4);

The complete source code of the program is presented below.

using System;

namespace CSharpSchool

{

class Test

{

delegate int MyDelegate(int p, int q);

static void Main()

{

MyDelegate arithMethod = new MyDelegate(Add);

173

Programmers Heaven: C# School

int r = arithMethod(3, 4);

Console.WriteLine("The result of arithmetic operation `+' on 3 and 4 is: {0}", r);

}

static int Add(int a, int b)

{

return a + b;

}

}

}

The result of the above program will be

The result of arithmetic operation `+' on 3 and 4 is: 7

Press any key to continue

The above program can be changed so that the arithmetic operation can be selected by the user.

using System;

namespace CSharpSchool

{

class Test

{

delegate int MyDelegate(int p, int q); static void Main()

{

MyDelegate arithMethod = null;

Console.WriteLine("Which arithmetic operation you like to perform on 3 and 4?");

Console.WriteLine("Press

+

for

Add

");

Console.WriteLine("Press

-

for

Subtract

");

Console.Write("Press m for Maximum Number "); char choice = (char) Console.Read();

switch(choice)

{

case '+':

arithMethod = new MyDelegate(Add); break;

case '-':

arithMethod = new MyDelegate(Subtract);

174

Programmers Heaven: C# School

break; case 'm':

arithMethod = new MyDelegate(Max); break;

}

int r = arithMethod(3, 4);

Console.WriteLine("\nThe result of arithmetic operation {0} on 3 and 4 is: {1}", choice, r);

}

static int Add(int a, int b)

{

return a + b;

}

static int Subtract(int a, int b)

{

return a-b;

}

static int Max(int c, int d)

{

if(c>d) return c;

else return d;

}

}

}

Here we have defined three methods with the same signature; Add(), Subtract() and Max(). A delegate type called MyDelegate is defined so that its reference arithDelegate can point to any method with a matching signature. The delegate reference 'arithDelegate' is used to point out the particular method based on the user input at runtime. The sample output of the code is:

Which arithmetic operation you like to perform on 3 and 4? Press + for Add

Press - for Subtract

Press m for Maximum Number -

The result of arithmetic operation - on 3 and 4 is: -1

Press any key to continue

175

Соседние файлы в папке books