1. What is event in C #
Simplely speaking, event in C # Is that as one instance does one behaviour, it will receive the message and then react with the message.
2. event happening & re-acting mechanic
3. How to declare a event
I. first declare a delegte
Ii. Secondly declare repective event
Like the following codes:
Public Delegate voidMynewevent (| object sender |, | myeventargs E | );
Public eventMynewevent Onmynewevent;
4. Event Demo project
E. g. Cat & mouse problem.
A mouse wanna steal something, at the same time, a cat is tracking him. once the mouse is stealing, it will touch something and make noise. and then, the cat will know the mouse is stealing and receive the message and re-act at once. please create a project to realiaze This schema.
The codes are following:
Namespace catmouse
{
public class mouse
{< br> Public Delegate void mousesteel (string food);
public event mousesteel onmousesteel; // declare an event
Public void mouseissteeling (string food)
{
Console. writeline ("sender side: I am a mouse, I am steeling {0} \ n", food );
If (onmousesteel! = NULL)
// If there exists a listener who is listen to this event, onmousesteel object will not be null; else it will be null;
Onmousesteel (food );
}
}
public class cat
{< br> Public CAT (mouse tmp_mouse)
{< br> This. a_mouse = tmp_mouse;
a_mouse.onmousesteel + = new mouse. mousesteel (a_mouse_onmousesteel);
// once the mouse is stealing, the cat will re-act by method
}
Void a_mouse_onmousesteel (string food)
{
Console. writeline ("Runner er side: cat! A mouse is steeling {0} \ n ", food );
}
Private mouse a_mouse;
}
Class Program
{
Static void main (string [] ARGs)
{
Mouse a_mouse = new mouse ();
Cat a_cat = new CAT (a_mouse );
A_mouse.mouseissteeling ("Bread ");
A_mouse.mouseissteeling ("fish ");
A_mouse.mouseissteeling ("milk ");
A_mouse.mouseissteeling ("butter ");
Console. Read ();
}
}
}
And if everything works well, we will such window:
Congratulations!