0
What 's the usefull of delegate and event in c#
2 odpowiedzi
+ 1
By events you can avoid checking the state of an object waiting something to change on it. Using them you register a listener for the event, and instead of hundreds of wasted checks you will get notified only when the event is triggered by the given object.
Also, this makes scripting more easy in general:
int score = 0;
public void SpawnEnemy() {
Enemy newEnemy = new Enemy();
newEnemy.Died += (e) => {
score += 10;
player.Tell("You killed " + e.Name
+ "! +10 points!");
}
}
Events are for notifier purposes. Delegates do declare signature. You can define an event the following way:
public class Enemy {
//. . .
//the signature:
public delegate void EnemyListener(Enemy e);
//event using the signature:
public event EnemyListener Died;
//methods listening to this event
//must have the given signature
}
You trigger it like that:
public class Enemy {
//. . .
public void Hurt(int damage) {
health -= damage;
if (health <= 0) {
if (Died != null)
Died(this);
}
}
}
(The "if (Died != null)" checks if anyone listens to the event. If not, then by triggering the event a NullReferenceException whould be thrown, so always check != null before calling an event!)
So, instead of this:
interested --checks---> subject
interested --checks---> subject
interested --checks---> subject
...
interested --checks---> subject
- subject passes requirement
interested does something
You do:
interested --registers--listener--> subject
*later on*
subject changes state
subject triggers event
---> notify: interested
interested does something
0
wlh délégation mli7a l programmation mli7a lkolch