classcat{Private string_name; PublicCat (stringname) {_name=name; } Public voidShout () {Console.WriteLine ("aim, I am"+_name+", here I come! "); Catshout (); //step three, trigger point, event to parentheses } Public Delegate voidCatshouteventhandler ();//The first step, declaring the delegate, is to add parentheses Public EventCatshouteventhandler catshout;//The second step, declaring the event, type of the delegate type above}classmouse{ Public string_name; PublicMouse (stringname) {_name=name; } Public voidRun () {Console.WriteLine ("The cat is coming, I am"+_name+", Run! "); }}Static voidMain (string[] args) {Cat Cat=NewCat ("Tom"); Mouse Jerry=NewMouse ("Jerry"); Mouse Jack .=NewMouse ("Jack"); Cat. Catshout+=NewCat.catshouteventhandler (Jerry. Run);//The fourth step is to register the delegate of the relevant method with the eventCat. Catshout + =NewCat.catshouteventhandler (Jack. Run); Cat. Shout (); Console.ReadLine ();}
Delegates and Events C # demo code