C # programming: Examples of delegated programs

Source: Internet
Author: User

C # programming: Examples of delegated programs

A delegate is not a method. It is a special type used to call a method that has the same signature as the delegate (signature here refers to the parameter list of the method.

An important feature of delegation is that a delegate does not need to care about the object type of the method when calling a method. It only requires that the provided method signature matches the delegate signature.

Delegate declaration format: modifier delegate return type delegate name (parameter list)

Public delegate void BTEvent ();

An example is provided:

Using System; using System. collections. generic; using System. linq; using System. text; namespace delegate {public class ZhangXiaoSan {// actually, the ticket is a small public static void BuyTicket () {Console. writeLine ("Buy a ticket! ");} Public static void BuyMovieTicket () {Console. WriteLine (" buy movie tickets! ");} Public static void BuyStocksTicket () {Console. WriteLine (" buy stock! ") ;}} Class Program {// declare a delegate // delegate declaration format: modifier delegate return type delegate name (parameter list) public delegate void BTEvent (); static void Main (string [] args) {Console. writeLine ("============= single delegate ==========="); BTEvent myDelegate = new BTEvent (ZhangXiaoSan. buyTicket); myDelegate (); // call the delegate Console. writeLine ("============= delegate merging ==============="); // can be merged during delegation, the merge of the delegate is called multicast myDelegate + = ZhangXiaoSan. buyMovieTicket; myDelegate + = ZhangXiaoSan. buyStocksTicket; myDelegate (); // call the delegate Console. writeLine ("============ cancel the delegate =============="); myDelegate-= ZhangXiaoSan. buyMovieTicket; myDelegate (); // call the delegate Console. readKey ();}}}


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.