C # Delegate tutorials and sample demos

Source: Internet
Author: User

What is a delegate
Popular Explanation: a delegate is a pointer to a method that fits a format (method signature)
Self-Understanding: A delegate is defined as a variable to hold a method, the delegate can hold multiple methods, in the call, the added order to execute the added method

Understanding of the delegation
in fact, the delegate is similar to the C language pointer, he is a data type name, such as int, double, etc., except that the pointer type is the method of storing. The delegate itself is a class that can be written inside the class or outside of the class, itself a syntactic sugar, compiled into a class at compile time.
Role of the delegate
because the delegate is a data type that holds the method, the role of the delegate is as follows
  1. To use a method as a parameter
  2. Use method as return value
  3. To use a method as an external property
Using delegates
because the delegate itself is a class, it takes a few steps to use it
  1. Declaring a delegate
  2. To create a delegate object
  3. Invoke delegate
* Delegate Example
1. Sorting

There is a dog class, the Dog Class attribute has Name, age as follows:

    public class Dog    {        private string name;        public string name        {            get {return Name;}            set {name = value;}        }        private int age;        public int Age        {            get {return-age;}            set {age = value;}        }    }

Create multiple objects for this dog class and store them in the generic of list, as follows:

            list<dog> list = new list<dog> ();            List. ADD (New Dog () {Name = "small black", age = n});            List. ADD (New Dog () {Name = "small green", age = 2});            List. ADD (New Dog () {Name = "small white", age = $});            List. ADD (New Dog () {Name = "xiaoqing", age = 34});

Requirement: Now we need to sort the puppies in this generic collection by age, there are two solutions, 1. Using interfaces; 2. Using a delegate; 3. Using Lamda expressions

In the list collection, there is a sorted method of sort (), with 4 overloads, as follows:

    1. public void Sort ();
    2. public void Sort (comparison<t> Comparison);
    3. public void Sort (icomparer<t> comparer);
    4. public void Sort (int index, int count, icomparer<t> comparer);
Here, 1, 4, not elaborated, the main explanation 2,3


1. Use the interface to sort.

public void Sort (icomparer<t> comparer);

The method is to sort the objects using an interface implementation


Explain:

IComparer is an interface whose interface implements a compare method that specifies the condition of the ordering, and the interface is defined as follows:

    Summary:     //     defines the method that the type implements to compare two objects. ////    type parameter:     //   T:    //     type of object to compare. Public    interface Icomparer<in t>    {        //Summary:         //     compare two objects and return a value indicating whether an object is less than, equal to, or greater than another object. ////        Parameters:         //   x://     The first object to compare. ////   y:        //     The second object to compare. /////        Returns the result:         //     A signed integer that indicates the relative value of x and Y, as shown in the following table. The value meaning is less than 0 x less than Y. 0 x equals Y. Greater than 0 x is greater than Y.        int Compare (t x, t y);    }

So, when we use interfaces, we define a class Comparedog to inherit this interface, and the conditions for sorting are sorted by the age attribute in the object, and the code is as follows:

    public class comparedog:icomparer<dog>    {public        int Compare (dog x, dog y)        {            return x.age-y.age;< c5/>}    }

In this case, we can use the sort (icomparer<t> comparer) method to sort the collection, where the parameter is the Comparedog class defined above, which implements the IComparer interface.

List. Sort (new Comparedog ());//This enables the sorting of collections

2. Use the delegate to sort public void sort (comparison<t> Comparison);
This method is to use a delegate to sort the collection
Explanation: Comparison is actually a delegate type, defined as follows:
    Summary:     //     represents a method that compares two objects of the same type. ////    Parameters:     //   x://     The first object to compare. ////   y:    //     The second object to compare. ////    type parameter:     //   T:    //     type of object to compare. /////    Returns the result:     //     A signed integer that indicates the relative value of x and Y, as shown in the following table. Value meaning less than 0x less than Y. 0x equals Y. Greater than 0x is greater than Y. Public    Delegate int comparison<in t> (t x, t y);

Since it is a parameter of the delegate type, then we will write a method that conforms to the delegate and specify the conditions for the ordering, the code is as follows:
        int Comparison (dog x, dog y)        {            return x.age-y.age;        }

So, when we sort, we just need to pass this method in the top as an argument:
List. Sort (Comparison);

3. Using LAMDA Expressions In fact, the essence of the LAMDA expression is a delegate, but Microsoft turned it into a syntactic sugar, convenient for the use of programmers, here is not much elaboration, the code can be implemented as follows:
List. Sort ((x, y) =>x.age-y.age);


2. Ask for maximum value: An array of type int to find the maximum

We do it in the usual way, and then we implement it using a delegate.


int[] Arrint = new Int[5] {1,3,8,4,2};

General thought:

Define a method, pass in the array as a parameter, and loop through the array, and take the maximum value, as follows:

        int MaxInt (int[] arr)        {            int MaxInt = arr[0];            for (int i = 1; i < arr. Length; i++)            {                if (MaxInt < arr[i])                {                    maxInt = Arr[i];                }            }            return maxInt;        }

Call:

            int[] Arrint = new Int[5] {1,3,8,4,2};            int max = MAXINT (arrint);


Note: The above custom method can achieve the maximum value of int type data, then if the maximum value of double type is obtained? String length of type string?  object to the maximum value according to the specified property? In this case, you have to write a method that is logically achievable for every situation, but using a delegate can be a better approach.


Delegate implementation

Define a generic method, pass in an array as a parameter, and pass in the comparison<t> type as the delegate of the comparison, the delegate has been explained above, the code is as follows:

       T maxvalue<t> (t[] arr,comparison<t> func)        {            T maxInt = arr[0];            for (int i = 1; i < arr. Length; i++)            {                //Use delegates to compare                if (func (MaxInt, Arr[i]) < 0)                {                    maxInt = Arr[i];                }            }            return maxInt;        }

Invocation: The delegate method parameter here uses the LAMDA expression to represent

            Maximum number of            int[] Arrint = new Int[5] {1,3,8,4,2};            int max = maxvalue<int> (Arrint, (x, y) = × X-y);            string of the maximum string length            string[] arrstr = new string[] {"AA", "FCC", "TGTGC"};            String maxlenght = Maxvalue<string> (Arrstr, (x, y) = = x.length-y.length);            By age, the oldest object in the collection of objects            dog[] dogs = new dog[] {new Dog () {name = "small Black", ages = 2}, new Dog () {name = "small LV", age =} , new Dog () {name = "Little Bai", age = +}, new Dog () {name = "Small Qing", age = $}};            Dog Maxdog = maxvalue<dog> (dogs, (x, y) = = X.age-y.age);


Do not like to spray, welcome to comment!


C # Delegate tutorials and sample demos

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.