Examples of C # delegates and events explained

Source: Internet
Author: User

Using System;namespace delegate_event{//define a cat class cat{//define a Name field private string name;//create constructor, parameter string, give Kitty an initial name If the initialization does not write the name will be an error, unless you write another reload public Cat (string name) {this.name = name;} Define a delegate, name casually public delegate void Catshoutdelegate ();//define an event, the type of the event is the name of the delegate public event Catshoutdelegate catshoutevent;//defines a method that a cat calls public void shout () {Console.WriteLine ("Meow ~, I am {0}", name);/////////////////////////When executing a cat-called method, determine if the instance object exists// When an instance object is present, it means that the event has already occurred//this time the method of the delegate is executed, the main function is what method of the delegate executes what method if (catshoutevent! = null) {//Executes the event's delegate, Is the indirect execution of the 2 mouse Run Method catshoutevent ();}} Class Mouse{private string Name;public Mouse (string name) {this.name = name;} public void Run () {Console.WriteLine ("Run! "+ name+" The old cat is coming! ");}} Class Mainclass{public static void Main (string[] args) {Cat cat1 = new Cat ("Tom"); Mouse mouse1 = new Mouse ("Jerry"); Mouse mouse2 = new Mouse ("Jack"),//indicates that the method of the Mouse1 run is delegated to catshoutdelegate through an instance of the event catshoutevent registered to the cat. + = is to add the meaning of the event cat1. Catshoutevent + = new Cat.catshoutdelegate (mouse1. Run); cat1. Catshoutevent + = newCat.catshoutdelegate (Mouse2. Run); cat1. Shout (); Console.read ();}}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Examples of C # delegates and events explained

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.