Let's use a simple example to illustrate the mechanism of this message passing.
There is a family of three, the mother is responsible for cooking, father and children eat ... Think of these three people as three classes.
Mother has a method called "cooking". There is an event called "Dinner". After the meal, call the development event and post the dinner message.
Father and child have a method, called "Eat".
The father and the children's "eat" method, registered to the mother's "Dinner" event. That is, subscribe to Mom's dinner message. Let mom finish dinner, when the news, tell Dad and children.
This mechanism is in C #, subscription publishing. Here's what we do with code:
1 class Program2 {3 Public Static voidMain (string[] args)4 {5 //instantiating an object6Mom mom =NewMom ();7Dad dad =NewDad ();8Child child =NewChild ();9 Ten //register your father and child's Eat method with your mother's Eat event One //Subscribe to the news of Mom's dinner AMom. Eat + =Dad. Eat; -Mom. Eat + =Child . Eat; - the //call Mom's Cook event - mom. Cook (); - -Console.Write ("Press any key to continue ..."); +Console.readkey (true); - } + } A at Public classMom - { - //define eat events for post meal messages - Public EventAction Eat; - - Public voidCook () in { -Console.WriteLine ("Mom: Dinner's ready."); to //Dinner 's ready, post dinner message + Eat (); - } the } * $ Public classDadPanax Notoginseng { - Public voidEat () the { + //dad, go eat. AConsole.WriteLine ("dad: it's dinner. "); the } + } - $ Public class Child $ { - Public voidEat () - { the //bear Children lol, after the fight to eat -Console.WriteLine ("Child: Finish the game and eat. ");Wuyi } the}
Operation Result:
What do you do when Grandpa and Grandma come to the guest? And the father and the child, write a eat method, the same registration to the mother's dinner event is good.
Events in C #-subscriptions and publications