C # differences between delegate and event,

Source: Internet
Author: User

C # differences between delegate and event,

In general, a delegate is a class that maintains a field internally and points to a method. An event can be considered as a delegate type variable. Multiple delegates or methods can be registered or canceled through the event. This document describes the differences between the two methods by Delegate and event execution.

 

□Delegate execution Method

    class Program
    {
        static void Main(string[] args)
        {
            Example example = new Example();
            example.Go();
            Console.ReadKey();
        }
    }
    public class Example
    {
        public delegate void DoSth(string str);
        internal void Go()
        {
// Declare a delegate variable and use known methods as parameters of its constructor
            DoSth d = new DoSth(Print);
            string str = "Hello,World";
// Call the static method Invoke to trigger the delegate.
            d.Invoke(str);
        }
        void Print(string str)
        {
            Console.WriteLine(str);
        }
    }

Above,

○ During CLR running, the delegate dosomething is actually a class. This class has a constructor of the method type and provides an Invoke instance method to trigger the execution of the delegate.
○ Delegate dosomething defines the parameters and return TYPES OF THE METHOD
○ By entrusting the dosomething constructor, you can assign a value to the constructor that complies with the definition.
○ Call the entrusted instance method Invoke executes the Method

 

However, in fact, there is another way for the delegate execution method: Delegate variable (parameter list)

    public class Example
    {
        public delegate void DoSth(object sender, EventArgs e);
        internal void Go()
        {
// Declare a delegate variable and use known methods as parameters of its constructor
            DoSth d = new DoSth(Print);
            object sender = 10;
            EventArgs e = new EventArgs();
            d(sender, e);
        }
        void Print(object sender, EventArgs e)
        {
            Console.WriteLine(sender);
        }
    }

Above,

○ The parameter list of delegate dosomething is consistent with that of method Print.
○ The parameter object sender in the delegate dosomething is usually used to represent the initiator of an action, and EventArgs e is used to represent the parameter of an action.

In fact, the delegate variable (parameter list), the event is executed in this form.

 

□Event execution Method

    public class Example
    {
        public delegate void DoSth(object sender, EventArgs e);
        public event DoSth myDoSth;
        internal void Go()
        {
// Declare a delegate variable and use known methods as parameters of its constructor
            DoSth d = new DoSth(Print);
            object sender = 10;
            EventArgs e = new EventArgs();
            myDoSth += new DoSth(d);
            myDoSth(sender, e);
        }
        void Print(object sender, EventArgs e)
        {
            Console.WriteLine(sender);
        }
    }

Above,

○ Declares the event mydosomething. The event type is the dosomething delegate.
○ Event registration delegate through + =
○ Register a delegate instance for an event using the constructor entrusted by dosomething
○ Use the form of delegate variable (Parameter List) to let the event be executed

 

In addition, you can register multiple delegates for the event through + =.

   public class Example
    {
        public delegate void DoSth(object sender, EventArgs e);
        public event DoSth myDoSth;
        internal void Go()
        {
// Declare a delegate variable and use known methods as parameters of its constructor
            DoSth d = new DoSth(Print);
            DoSth d1 = new DoSth(Say);
            object sender = 10;
            EventArgs e = new EventArgs();
// Register multiple delegates for the event
            myDoSth += new DoSth(d);
            myDoSth += new DoSth(d1);
            myDoSth(sender, e);
        }
        void Print(object sender, EventArgs e)
        {
            Console.WriteLine(sender);
        }
        void Say(object sender, EventArgs e)
        {
            Console.WriteLine(sender);
        }
    }

 

The above code registers one or more delegate instances for the event through + =. In fact, you can also directly register the method for the event.

    public class Example
    {
        public delegate void DoSth(object sender, EventArgs e);
        public event DoSth myDoSth;
        internal void Go()
        {
            object sender = 10;
            EventArgs e = new EventArgs();
// Register multiple delegates for the event
            myDoSth += Print;
            myDoSth += Say;
            myDoSth(sender, e);
        }
        void Print(object sender, EventArgs e)
        {
            Console.WriteLine(sender);
        }
        void Say(object sender, EventArgs e)
        {
            Console.WriteLine(sender);
        }
    }    

 

□Execution method through EventHandler

Let's take a look at the source code of EventHandler.

It can be seen that EventHandler is the delegate. Now you can use EventHandler to execute multiple methods.

    public class Example
    {
        public event EventHandler myEvent;
        internal void Go()
        {
            object sender = 10;
            EventArgs e = new EventArgs();
// Register multiple delegates for the event
            myEvent += Print;
            myEvent += Say;
            myEvent(sender, e);
        }
        void Print(object sender, EventArgs e)
        {
            Console.WriteLine(sender);
        }
        void Say(object sender, EventArgs e)
        {
            Console.WriteLine(sender);
        }
    }

 

Summary:
○ A delegate is a class that can also be instantiated. The Delegate constructor assigns a method to the delegate instance.
○ There are two ways to trigger a delegate: delegate instance. Invoke (parameter list) and delegate instance (parameter list)
○ Events can be viewed as a delegate-type variable.
○ Use + = to register multiple delegate instances or methods for an event
○ Use-= to deregister multiple delegate instances or multiple methods for the event
○ EventHandler is a delegate

 

 


In C language-> what?

-> Is a whole. It is used to point to a struct, class in C ++, and other pointers containing sub-data to obtain sub-data. In other words, if we define a struct in C and declare a pointer pointing to this struct, we need to use "->" to retrieve the data in the struct using the pointer ".
For example:
Struct Data
{
Int a, B, c;
};/* Define struct */
Struct Data * p;/* define struct pointer */
Struct Data A = {1, 2, 3};/* declare variable */
Int x;/* declare a variable x */
P = & A;/* point p to */
X = p-> a;/* indicates that the data item a in the struct pointed to by p is assigned to x */
/* Because p points to A, p-> a = A. a, that is, 1 */

For the first problem, p = p-> next; this should appear in the linked list of C language. next here should be a struct pointer of the same type as p, and its definition format should be:
Struct Data
{
Int;
Struct Data * next;
};/* Define struct */
............
Main ()
{
Struct Data * p;/* declare the pointer Variable p */
......
P = p-> next;/* assign the value in next to p */
}
The linked list pointer is a difficulty in C language, but it is also the key. It is very useful to learn it. To be careful, you must first talk about variables and pointers.
What is a variable? The so-called variables should not be simply thought that the amount will become a variable. Let's use the question of our Dean: "Is the classroom changing ?" Change, because there are different people in the classroom every day, but they do not change, because the classroom is always there, and it does not become larger or smaller. This is the variable: There is a constant address and a variable storage space. Under normal circumstances, we only see the variable in the room, that is, its content, but do not pay attention to the variable address, but the C language pointer is the address of the room. We declare that variables are equivalent to building a house to store things. We can directly watch things in the house, while declaring pointers is equivalent to getting a positioner. When a pointer points to a variable, it is to use the pointer to locate the variable. Then we can use the pointer to find the variable "tracked" and get the content in it.
What about struct? The structure is equivalent to a villa composed of several houses, and several houses are bound for use together. Suppose there are many such villas distributed in a big maze, and each villa has a house. The location information of another villa is put in it. Now you have found the first villa with the positioner and obtained what you want from it (the data part of the linked list ), then, calculate the location of the next villa into your positioner (p = p-> next), and go down to the next villa ...... If you go on like this, you will know that the information of a villa on the ground is gone (p-> next = NULL), and your trip is over. This is the process of traversing a linked list. Now you can understand the meaning of p = p-> next!
Write so much. I hope you can understand.
If you want to learn c and C ++ well, you must be familiar with linked lists and pointers!

In C language-> what?

-> Is a whole. It is used to point to a struct, class in C ++, and other pointers containing sub-data to obtain sub-data. In other words, if we define a struct in C and declare a pointer pointing to this struct, we need to use "->" to retrieve the data in the struct using the pointer ".
For example:
Struct Data
{
Int a, B, c;
};/* Define struct */
Struct Data * p;/* define struct pointer */
Struct Data A = {1, 2, 3};/* declare variable */
Int x;/* declare a variable x */
P = & A;/* point p to */
X = p-> a;/* indicates that the data item a in the struct pointed to by p is assigned to x */
/* Because p points to A, p-> a = A. a, that is, 1 */

For the first problem, p = p-> next; this should appear in the linked list of C language. next here should be a struct pointer of the same type as p, and its definition format should be:
Struct Data
{
Int;
Struct Data * next;
};/* Define struct */
............
Main ()
{
Struct Data * p;/* declare the pointer Variable p */
......
P = p-> next;/* assign the value in next to p */
}
The linked list pointer is a difficulty in C language, but it is also the key. It is very useful to learn it. To be careful, you must first talk about variables and pointers.
What is a variable? The so-called variables should not be simply thought that the amount will become a variable. Let's use the question of our Dean: "Is the classroom changing ?" Change, because there are different people in the classroom every day, but they do not change, because the classroom is always there, and it does not become larger or smaller. This is the variable: There is a constant address and a variable storage space. Under normal circumstances, we only see the variable in the room, that is, its content, but do not pay attention to the variable address, but the C language pointer is the address of the room. We declare that variables are equivalent to building a house to store things. We can directly watch things in the house, while declaring pointers is equivalent to getting a positioner. When a pointer points to a variable, it is to use the pointer to locate the variable. Then we can use the pointer to find the variable "tracked" and get the content in it.
What about struct? The structure is equivalent to a villa composed of several houses, and several houses are bound for use together. Suppose there are many such villas distributed in a big maze, and each villa has a house. The location information of another villa is put in it. Now you have found the first villa with the positioner and obtained what you want from it (the data part of the linked list ), then, calculate the location of the next villa into your positioner (p = p-> next), and go down to the next villa ...... If you go on like this, you will know that the information of a villa on the ground is gone (p-> next = NULL), and your trip is over. This is the process of traversing a linked list. Now you can understand the meaning of p = p-> next!
Write so much. I hope you can understand.
If you want to learn c and C ++ well, you must be familiar with linked lists and pointers!

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.