Delegate in C #

Source: Internet
Author: User

The first time I came into contact with delegation in programming languages, I felt very unfamiliar. After several examples, we found that the delegation in the object-oriented language is the same as in our real life. For example, Xiaohong needs to go to the bank to get the money. Here, it is the method of Xiaohong. Similarly, if James is, he can also get the money. If Xiao Hong asks Xiao Ming to take money for her due to some issues, it is delegated here. That is, James uses the same method to get money in the name of Xiaohong.

In C #, the Delegate is derived from the base class System. delegate. However, the Delegate definition is different from the conventional definition method. The delegate is defined by the keyword Delegate:

Public delegate void myDelegate (int x, int y)

The code above defines a new delegate, which can encapsulate any method that returns an int with two int parameters, whether it is an instance method or a static method, as long as their signatures (the order of parameter types in a method) are the same as the defined delegate, they can be encapsulated into the delegate.

Here is a specific example:

For ease of understanding, I declare a specific class here.

Public delegate void GetMoney (string name); // defines the delegate class Example2 {public static void getCCBmoney (string name) {Console. WriteLine ("get money from CCB! ");} Public static void getABCmoney (string name) {Console. WriteLine (" get the money from ABC! ");} Static void Main (string [] agrs) {GetMoney gm; gm = getABCmoney; // delegate instantiation, Or you can write it as GetMoney gm = new GetMoney (getABCmoney) gm ("Xiaohong ");}}

The output result is as follows:


From the above example, we can sum up that a delegate is a class that defines the type of the method and can pass the method as a parameter. This dynamic parameter-based approach is assigned, this greatly improves program scalability.

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.