Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
4
Roughly speaking: a delegate stands in
for an actual method
1. Define the prototype (the heading) of the actual method the delegate
will stand for.
2. Then define a delegate.
3. Then tell the system for which actual method the delegate stands
for.
During runtime you may change the actual method the delegate stands
for.
5
An example of using a delegate
public int CalcAddingAnswer public int CalcMultiplyingAnswer
(int a, int b) (int a, int b)
{ return a + b; } { return a * b; }
a = CalculateRightAnswer(4,5);
//Now the actual method CalcAddingAnswer, with the values 4 and 5 for
its parameters, is performed. So the return-value is 9.
Demo: show it ! ! !
6
Possibilities with and limitations of
delegates
1. “Calling the delegate means calling the actual method”.
Who can do the calling? Everybody who can access it (depending
on the access-modifier).
2. “Tell the system for which actual method the delegate stands for”.
Suppose a delegate stands for no actual method. What happens
when you call the delegate now?
Answer: an exception.
8
Events
Events:
1. Who can do the calling? ONLY from inside this object (NOT
depending on the access-modifier).
2. Can you assign an actual method from outside the class to an
event? Depends on its access-modifier.
3. Can an event stand for 0, 1 or more actual methods?
Yes, the same as for a delegate.
9
Events
Objects should take care of themselves; just notify the others, who are
interested in you.
An example:
10
Example
public class Motorbike
{
private int speed;
private int maxSpeed;
11
Example
public class Motorbike
{
private int speed;
private int maxSpeed;
12
Example
public class Motorbike
{
SpeedChanged(this, this.speed);
13
Example
public class Motorbike
{
14
Example
In another class:
ValentinosBike.SpeedLimitExceeded +=
new Motorbike.SpeedChangedHandler(this.ShowInListbox);
In the example:
SpeedChanged(this, this.speed); // wrong
if (SpeedChanged!=null)
{
SpeedChanged(this, this.speed);
}
// correct
16
Another remark about events
There is a difference between
(a) ValentinosBike.SpeedLimitExceeded +=
new Motorbike.SpeedChangedHandler(this.ShowInListbox);
and
(b) ValentinosBike.SpeedLimitExceeded =
new Motorbike.SpeedChangedHandler(this.ShowInListbox);
(a):
If the event does not exist, it is created and the delegate-object is added
to it. If the event already exists, the delegate-object is added to it.
(b):
NOT possible for an event; it is possible for a delegate.
If the delegate does not exist, it is created and the delegate-object is
added to it. If the delegate already exists, all already attached delegate-
objects are removed and the new delegate-object is added to it.
17
Here's is one more remark about events
Removing:
ValentinosBike.SpeedLimitExceeded -=
new Motorbike.SpeedChangedHandler(this.ShowInListbox);
18