Delegate in C # (Personal organization ),

Source: Internet
Author: User

Delegate in C # (Personal organization ),

Delegate

1. What is delegation?

A delegate is a reference type, which is a managed version of the function pointer. In C #, delegation is a type that stores references as functions. A delegate can reference instances and static methods, while a function pointer can only reference static methods. A Delegate Declaration is very similar to a function. Unlike a function, a Delegate does not contain a function body and requires the Delegate keyword. The delegate declaration specifies a function signature, which includes the parameter list and a return type. After the delegate is defined, you can declare the variable of the delegate type, and then initialize the variable as a function with the same signature as the delegate for reference, you can then use the delegate variable to call this function. (Ps: Actually, the delegate is a class. Its purpose is to pass methods as parameters of other methods !)

Although the delegate is very similar to the function pointer, it is not a pointer. Many people regard the delegate in. NET as a safe function pointer, which is far-fetched. The delegate implementation function is very similar to the function pointer, which provides a program callback mechanism.

Ii. IV. Delegation: 1. Declaring delegation types

2. There is a method that contains the executed code

3. Create a delegated instance

4. Call the delegated instance

Iii. Example: (1)

Using System; namespace ConsoleApp {class Program {// 1. Declare the delegate Type public delegate void AddDelete (int a, int B ); // 2. There is a method that contains the executed code public static void Add (int a, int B) {Console. writeLine (a + B);} static void Main (string [] args) {// 3. Create a delegate instance. The new keyword is used, indicating that the delegate is also a class, bind the method name Add as a parameter to the delegate instance var adddelete = new AddDelete (Add); // 4. Call the delegate instance adddelete (1, 2); Console. readKey ();}}}

(2) Use the anonymous method, as shown in the following figure. You do not need to define an Add function,

using System;namespace ConsoleApp{    class Program    {        public delegate void AddDelete(int a, int b);        static void Main(string[] args)        {            AddDelete adddelete = delegate(int a, int b) { Console.WriteLine(a + b); };            adddelete(1,2);            Console.ReadLine();        }    }}

4. Must the delegate method in C # be static?

 

using System;namespace ConsoleApp{    class Program    {        public delegate void AddDelete(int a, int b);        private class MyClass        {            public void Add(int a, int b)            {                Console.WriteLine(a + b);            }        }                static void Main(string[] args)        {            MyClass myClass=new MyClass();                      var adddelete = new AddDelete(myClass.Add);                         adddelete(1, 2);            Console.ReadKey();        }    }}

 

The code above shows that the delegate can bind both static methods and instance methods. However, when binding an instance method, the target attribute of the delegate is set to an instance object of the type to which the instance method belongs. When a static method is bound, the target attribute of delegate is NULL.

 

5. What is multicast delegation?

Each delegate only contains one method call. The number of calls to the delegate is the same as the number of calls to the method. If you want to call multiple methods, you need to call the delegate multiple times. Of course, the delegate can also contain multiple methods. This delegate can be a multicast delegate.

In the call process: 1. the multicast delegate must reference more than one method and be of the same type.

2. The method contained in the multicast delegate must return void; otherwise, a run-time exception will be thrown and parameters cannot be included (but reference parameters can be included)

Example:

using System;namespace ConsoleApp{    public delegate int MyDel(int name);    class Program    {        static int Add1(int a)        {            var b = 10 + a;            Console.WriteLine(b);            return b;        }        static int Add2(int a)        {            var b = 10 - a;            Console.WriteLine(b);            return b;        }        static void Main(string[] args)        {            var add = new MyDel(Add1);            add += new MyDel(Add2);            Console.WriteLine(add(10));            Console.ReadKey();        }    }}

Maybe, when you see this piece of code, you will be surprised, + = won't assign a value to delegatesand again?

But I want to say that your worries are superfluous. In our previous understanding, the + = operator has the function of assigning values, but why is it the same as the above Code, this is different from your imagination. In fact, the + = Operator is overloaded, which is not generally understood as follows:
{
Int a = 0, B = 1;
A + = B; // At this time, a becomes 1
}

When a delegate is used, + = will be overloaded, and its function becomes to add a reference delegate method for the assigned delegate variable without affecting the assigned delegate variable.
That is to say, each time the + = Operator is used, the delegate variable will be added to a delegate method. For example, after the original delegate variable is assigned a value, the delegate variable is also used as the delegate for the two delegate methods at the same time, and they run in the same order as the order in which they are added.

 

 

Ps: This article is based on my understanding on the Internet. If your rights and interests are inadvertently violated, please contact me.

 

  

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.