C # Delegate (i)--Description and examples

Source: Internet
Author: User

There are five types under the C # namespace, namely:

class, construct, interface, enumeration, delegate.

A delegate is defined as one of the basic types in 5, which means that the code can write:

Using system;namespace test{    delegate void Printany ();    Class program    {public        printany handler;        void Printnumber ()        {            Console.WriteLine ("the");        }        static void Main (string[] args)        {program            test_01 = new program ();            Test_01.handler = Test_01.printnumber;            Test_01.handler ();            Console.read ();}}}    

After a simple test, you can see that the output is printed out.

Next I'll explain further what a delegate is.

The first step: the definition of a delegate

The definition of Baidu is--

A delegate is a class that defines the type of the method so that the method can be passed as a parameter to another method.

Three keywords can be extracted: class, type, delivery method

Classes and types have an understanding, then let's look at the delivery method.

1-1. Delivery method

It is common to write code in a function to pass various parameters, can be numeric types can be object types, but it involves the need to choose different pieces of code may need to write a long if. ElseIf. Else's selection statement.

Examples Show

For example, the following requirements:

Input: Name, National output: how to greet.

Analysis: People in different countries greet the way is not the same, China said "eat", the United Kingdom said "Hello".

The general code is as follows--

    Class Greetpeople    {        string Name;        string country;        Public Greetpeople (string name, String country)        {            name = name;        }        public void greeting ()        {            if (country = = "Enghlish")            {                englishgreeting ();            }            else if (country = = "Chinese")            {                chinesegreeting ();            }        }        public void englishgreeting ()        {            Console.WriteLine (Name);            Console.WriteLine ("Hello");        }        public void chinesegreeting ()        {            Console.WriteLine (Name);            Console.WriteLine ("Eat");        }        static void Main ()        {            greetpeople lilei = new Greetpeople ("Lilei", "中文版");            Lilei.greeting ();            Console.read ();}}}    

Changes in requirements:

Now the software will be published in 20 countries in different languages, now please modify the above code. You'll find that you're not just adding functions, but also having to greeting

To make changes, long if-else if-else statements are always unreliable; debugging the geeeting function in 20 countries will be a torment!!

Now introduce the delegate with the following code:

 

delegate void Greetinghandler ();    Class Greetpeople    {        string Name;        string country;        Public Greetpeople (string name, String country)        {            name = name;        }        public void greeting (Greetinghandler handler)        {            handler ();        }        public void englishgreeting ()        {            Console.WriteLine (Name);            Console.WriteLine ("Hello");        }        public void chinesegreeting ()        {            Console.WriteLine (Name);            Console.WriteLine ("Eat");        }        static void Main ()        {            greetpeople lilei = new Greetpeople ("Lilei", "中文版");            Lilei.greeting (lilei.englishgreeting);            Console.read ();        }    }

At this point, the greeting function is simply a trigger for the function, and the choice of the parameter "中文版" as the constructor in the second row of main is not providing valuable information. The risk here is that the state is not easy to write wrong, but the calling function is probably wrong.

The code changes slightly:

    delegate void Greetinghandler ();        Class Greetpeople {string Name;        String country;        private static dictionary<string, greetinghandler> countrydic = new dictionary<string, greetinghandler> ();            Static Greetpeople () {Countrydic.add ("中文版", englishgreeting);        Countrydic.add ("Chinese", chinesegreeting);            } public Greetpeople (string name, String country) {name = name;        Country = country;            } public void Greeting () {Greetinghandler handler;            Console.WriteLine (Name);            if (Countrydic.trygetvalue (country, out handler)) {handler (); } else {Console.WriteLine ("not published in the country!!            ");        } Console.WriteLine ();        } public static void Englishgreeting () {Console.WriteLine ("Hello"); } public static void ChineSegreeting () {Console.WriteLine ("Eat It");            } static void Main () {greetpeople Lilei = new Greetpeople ("Lilei", "中文版");            Greetpeople Feifei = new Greetpeople ("Feifei", "Africa");            Lilei.greeting ();            Feifei.greeting ();        Console.read (); }    }}

Add a dictionary to map the country directly to the corresponding calling function, call greeting directly to the dictionary call. It can be said that the basic realization of demand.

1-2. Multicast delegation

Now the demand has changed:

The software sold well will be exhibited at multinational conferences, asking all guests to greet each other at once;

This is the use of multicast delegation; Multicast delegation One call notifies multiple function executions, the code is modified as follows:

 delegate void Greetinghandler ();        Class Greetpeople {string Name;        String country;        private static dictionary<string, greetinghandler> countrydic = new dictionary<string, greetinghandler> ();            Static Greetpeople () {Countrydic.add ("中文版", englishgreeting);        Countrydic.add ("Chinese", chinesegreeting);            } public Greetpeople (string name, String country) {name = name;        Country = country;            } public void Greeting () {Greetinghandler handler;            Console.WriteLine (Name); if (country = = "All") {list<greetinghandler> templist = new List<greetinghandler> (C                Ountrydic.values);                    if (templist! = null && templist.count > 0) {handler = templist[0];             for (int i = 1; i < Templist.count; i++) {           Handler + = Templist[i];                } handler ();            }} else if (Countrydic.trygetvalue (country, out handler)) {handler (); } else {Console.WriteLine ("not published in the country!!            ");        } Console.WriteLine ();        } public static void Englishgreeting () {Console.WriteLine ("Hello");        } public static void Chinesegreeting () {Console.WriteLine ("Eat");            } static void Main () {greetpeople Lilei = new Greetpeople ("Lilei", "中文版");            Greetpeople Feifei = new Greetpeople ("Feifei", "Africa");            Greetpeople Leijun = new Greetpeople ("Leijun", "all");            Lilei.greeting ();            Feifei.greeting ();            Leijun.greeting ();        Console.read (); }    }

  

C # Delegate (i)--Description and examples

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.