Event mechanic in C #

Source: Internet
Author: User
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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.