The cat shouted, and the master was awakened, and all the little mice began to flee.
The first thing to think about is the event invocation method.
It is possible to call a pair of methods in a cat-called event.
However, when there are many events, it is not enough to write and forget.
You can't have 10,000 people when you call 10,000 methods.
So you should use a delegate to control
1. Define a delegate first
public delegate void Alerthandler ();
2. We'll define an event for this delegate.
public event Alerthandler Alertevent;
3. Reasoning Ideas
There are 3 things to do when the event executes.
It is
The kitten is going to scream
People to wake up
The mouse is going to run, so when you build three classes, you have to delegate a method to three classes.
Just tell yourself when the kitten's barking.
People awake, mice run, these two need rooms to tell them
Because it's all inside a room.
4 Setting up a console program
The code is as follows
Define the agent for the cat yelling event
public delegate void Alerthandler ();
Master Class
Class Human
{
The way the master was awakened
public void Wake ()
{
Console.WriteLine ("Master: The Dead cat does not bark");
}
}
Mouse type
Class Mouse
{
The way the mice were scared to pack
public void Run ()
{
Console.WriteLine ("Mouse: There is danger, run!" ");
}
}
Cat class
Class Cat
{
Cat Yelling Event
public event Alerthandler Alertevent;
Public Cat ()
{
How to execute cry when the cat yells
Alertevent + = new Alerthandler (Alert);
}
Cat yelling Event Execution Handler
public void Alert ()
{
Console.WriteLine ("Cat: Meow ... Meow ... ");
}
The way the cat yells
public void Cry ()
{
Events that trigger a cat shout
Alertevent ();
}
}
House class
Class House
{
There was a mouse, a cat and a Master in the house.
Public Mouse Mouse = new Mouse ();
Public Human Human = new Human ();
Public cat cat = new Cat ();
Because in a house, the cat shouting event will cause the mouse to "escape" and the host "awakened"
So here the mouse "escape" and the host "awakened" two ways to hook up to the cat shouting event.
Public house ()
{
Cat. Alertevent + = new Alerthandler (mouse. Run);
Cat. Alertevent + = new Alerthandler (human. Wake);
}
}
Make good use of delegates, events.
This is better than calling a pair of methods. As for where the good, programmers understand.
The calling method is as follows
There's a house.
House H = new House ();
The cat shouted.
H.cat.cry ();
Console.readkey ();
About a simple face question (. Net