Using System;namespace delegate_event{//define a cat class cat{//define a Name field private string name;//create constructor, parameter string, give Kitty an initial name If the initialization does not write the name will be an error, unless you write another reload public Cat (string name) {this.name = name;} Define a delegate, name casually public delegate void Catshoutdelegate ();//define an event, the type of the event is the name of the delegate public event Catshoutdelegate catshoutevent;//defines a method that a cat calls public void shout () {Console.WriteLine ("Meow ~, I am {0}", name);/////////////////////////When executing a cat-called method, determine if the instance object exists// When an instance object is present, it means that the event has already occurred//this time the method of the delegate is executed, the main function is what method of the delegate executes what method if (catshoutevent! = null) {//Executes the event's delegate, Is the indirect execution of the 2 mouse Run Method catshoutevent ();}} Class Mouse{private string Name;public Mouse (string name) {this.name = name;} public void Run () {Console.WriteLine ("Run! "+ name+" The old cat is coming! ");}} Class Mainclass{public static void Main (string[] args) {Cat cat1 = new Cat ("Tom"); Mouse mouse1 = new Mouse ("Jerry"); Mouse mouse2 = new Mouse ("Jack"),//indicates that the method of the Mouse1 run is delegated to catshoutdelegate through an instance of the event catshoutevent registered to the cat. + = is to add the meaning of the event cat1. Catshoutevent + = new Cat.catshoutdelegate (mouse1. Run); cat1. Catshoutevent + = newCat.catshoutdelegate (Mouse2. Run); cat1. Shout (); Console.read ();}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Examples of C # delegates and events explained