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 ();}}}