C # basic (2) Understanding of delegation and events

Source: Internet
Author: User

As jimmyzhang said: it is not easy for many people who have been in contact with C # for a long time to better understand delegation and events. They are like a hacker. People who have passed the hacker think it is too easy, and people who have never seen the delegate and event will feel different (bi) panic and uncomfortable.

Summary:

(1) When a class is delegated, it defines the type of the method so that the method can be passed as a parameter of another method. This dynamic method is paid to the parameter, it can avoid using a large number of statements such as if --- else switch in the program, and make the program highly scalable.

(2) delegate can be used to bind multiple methods to the same delegate variable. When this variable is called, all the bound methods can be called in sequence.

(3) There is nothing difficult to understand about an event. Declaring an event is similar to declaring an encapsulated delegate type variable.

Below is a simple example. Let's take a look:Don't think you can understand it after reading it. Do it yourself..

Public delegate void wenhaodelegate (string name );

Public class wenhao
{
Public event wenhaodelegate delegate1;
Public void iwenhao (string name)
{
If (delegate1! = Null) // if there is a method to register with the delegate variable
{
Delegate1 (name); // call the method by Delegate
}
}
}

Class Program
{

Public static void english (string name)
{
Console. WriteLine ("morning:" + name );
}

Public static void chinese (string name)
{
Console. WriteLine ("Good morning:" + name );
Console. Read ();
}

Static void Main (string [] args)
{
Wenhao mywenhao = new wenhao ();
Mywenhao. delegate1 + = english;
Mywenhao. delegate1 + = chinese;
Mywenhao. iwenhao ("Duan Yingjie ");
}
}

 

 

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.