Delegate and event in C #

Source: Internet
Author: User
Title delegate and event in C #sam1111 (original) keywords. NET, C #

Event is a very important concept in windows-based program design. Because in almost all Windows applications, there are a lot of asynchronous calls involved, such as responding to click Buttons, handling Windows system messages, and so on, which need to be done in the way of events. Even in the next generation development platform ——. NET is no exception.

So what is an incident? An event is a message sent by an object that indicates that a particular action has occurred, or that a particular condition has been established. For example, the user clicked the mouse, socket on the arrival of data. The object that triggers the (raise) event is called the sender of the event sender, and the object that captures and responds to the event is called the event's recipient (event receiver).

Here, we're going to discuss how to use custom events to implement our own asynchronous calls in. NET's mainstream development language C #.

In C #, the implementation of events depends on delegate, so it is necessary to understand the concept of delegate first.

Delegate

Delegate is a type in C # that is actually a class that holds a reference to a method. Unlike other classes, the delegate class can have a signature (signature), and it can only hold a reference to the method that matches its signature. The functionality it implements is very similar to the function pointers in C + +. It allows you to pass the method M of Class A to the object of another class B, so that the object of Class B can call this method M. However, compared with function pointers, delegate has many advantages that are not available in function pointers. First, a function pointer can only point to a static function, while delegate can refer to static functions and non-static member functions. When referencing a non-static member function, delegate not only holds a reference to this function's entry pointer, but also holds a reference to the class instance that called the function. Secondly, compared with function pointers, delegate is an object-oriented, type-safe, and reliable controlled (managed) object. That is, runtime can ensure that delegate points to an effective method, and you need not worry that delegate will point to an invalid address or a cross-border address.

Implementing a delegate is simple, with the following 3 steps to implement a delegate:

1. Declares a delegate object that should have the same parameter and return value type as the method you want to pass.

2. Create the delegate object and pass the function you want to pass in as a parameter.

3. In the place where you want to implement the asynchronous call, the method is invoked by the object created in the previous step.

The following is a simple example:



Using System;

public class Mydelegatetest

{

Step 1, declare the delegate object

public delegate void MyDelegate (string name);

This is the method we want to pass, and it has the same parameter and return value type as MyDelegate

public static void Mydelegatefunc (string name)

{

Console.WriteLine ("Hello, {0}", name);

}



public static void Main ()

{

Step 2, create the delegate object

MyDelegate MD = new MyDelegate (MYDELEGATETEST.MYDELEGATEFUNC);

Step 3, call delegate

MD ("sam1111");

}

}

The output is: Hello, sam1111

With delegate, let's take a look at how events are handled in C #.

in the C # Handling Events in

event handling in C # is actually a delegate with a special signature, as in the following way:

public delegate void MyEventHandler (object sender, MyEventArgs e);

Of these two parameters, sender represents the event sender, and E is the event argument class. The MyEventArgs class is used to contain event-related data, and all event parameter classes must derive from the System.EventArgs class. Of course, if your event does not contain parameters, then you can use the System.EventArgs class as an argument directly.

It is so simple, combined with the implementation of delegate, that we can boil down the implementation of a custom event to the following steps:

1. Defines the delegate object type, which has two parameters, the first argument is the event sender object, and the second parameter class object.

2. Defines the event argument class, which should derive from the System.EventArgs class. If the event takes no arguments, this step can be omitted.

3. Defines an event-handling method that should have the same parameter and return value type as the delegate object.

4. The event keyword is used to define an object, and it is also a delegate object.

5. Add an event to the event queue with the + = operator (the-= operator can remove the event from the queue).

6. Write the event trigger method where you need to trigger the event by calling delegate. In general, this method should be a protected access restriction that cannot be invoked as public, but can be inherited by the quilt class. Name is on EventName

7. Invoke the event trigger method to trigger the event where appropriate.

The following is a simple example:



Using System;



public class Eventtest

{

Step 1, define the delegate object

public delegate void MyEventHandler (object sender, System.EventArgs e);

Step 2 Omit

public class Myeventcls

{

Step 3, define the event-handling method, which has the same parameter and return value class//type as the delegate object

public void Myeventfunc (object sender, System.EventArgs e)

{

Console.WriteLine ("My event is ok!");

}

}

Step 4, use the event keyword to define the events object

Private event MyEventHandler MyEvent;



Private Myeventcls myecls;



Public Eventtest ()

{

Myecls = new Myeventcls ();

Step 5, add the event to the queue with the + = operator

This.myevent + = new MyEventHandler (myecls. MYEVENTFUNC);

}

Step 6, write the event trigger function in the form of calling delegate

protected void Onmyevent (System.EventArgs e)

{

if (myevent!= null)

MyEvent (this, e);

}



public void RaiseEvent ()

{

EventArgs e = new EventArgs ();

Step 7, triggering the event

Onmyevent (e);

}



public static void Main ()

{

Eventtest et = new eventtest ();

Console.Write ("Please input ' a ':");

string s = Console.ReadLine ();

if (s = = "a")

{

Et. RaiseEvent ();

}

Else

{

Console.WriteLine ("Error");

}

}

}



The output is as follows, bold for the user's input:

Please input ' a ': a

My event is ok!

Summary

Through the above discussion, we have largely understood the concepts of delegate and event, and how to use them in C #. In my opinion, delegate is a very important concept in C #, and it can make some fairly complicated problems simple by using them rationally. Sometimes I even feel that delegate can even have a pointer effect, except that you can't access the physical address directly. And the event is entirely based on delegate. Due to limited capacity, this article is only a simple discussion of the application of delegate and event, not in-depth, I hope this article can play a role. Really want to have a better understanding of these two concepts, or recommend that you look at MSDN.

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.