Delegate (delegate) c # simple example,

Source: Internet
Author: User

Delegate (delegate) c # simple example,

Delegate (delegate) c # simple example

Key points: the mode enables the dependency between the target and the observation to be loosely coupled and the notification will be automatically transmitted.
Example: After a player hits an enemy, a series of changes occur: An explosion occurs after the attack, and one enemy is missing ....


Namespace adapterpattern {public partial class observerDelegateForm: Form {public observerDelegateForm () {InitializeComponent (); BaseData. enemyNumber = 100;} private void btnDisplay_Click (object sender, EventArgs e) {ExplosionEvent explosionEvent = new ExplosionEvent (); // observer 1 Enemy enemy = new Enemy (); // observer 2 player p1 = new player1 (); p1.Update + = new EventHandler (explosionEvent. explosionMax ); // Delegate to the observer 1 p1.Update + = new EventHandler (enemy. decrease); // Add the observer 2 listBox1.Items to the delegate. add (p1.Display () ;}} public static class BaseData // data transfer station {public static string DisplayString {get; set ;} public static int EnemyNumber {get; set ;}} public delegate void EventHandler (); // delegate the event handler public abstract class player {public event EventHandler Update; // declare an event update protected virtual void Policy () // pair Add event Execution Notification {if (Update! = Null) {Update () ;}} public abstract string Display () ;}public class player1: player {public override string Display () {Policy (); // notification observer; return BaseData. displayString + BaseData. enemyNumber. toString () ;}} public class ExplosionEvent // observer 1 {public void ExplosionMax () {BaseData. displayString = "";} public void ExplosionMin () {BaseData. displayString = "show small explosion ";}//.....} public class Enemy // observer 2 {public void Decrease () {BaseData. enemyNumber-= 1; // "Reduce the number of enemies by 1 ";}//.....}}


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.